如何修复错误:对象作为 React 子对象无效

Jos*_*kaa 9 javascript reactjs

我正在学习 React,我正在尝试开发一个代码来从 api“Numbers API”中获取随机 10 个数字以及相应的有趣事实。

我面临的问题是,当我运行代码时,出现错误

“错误:对象作为 React 子项无效(发现:[object Promise])。如果您打算渲染子项集合,请改用数组”

下面我附上了代码:

const originalArray = new Array(10).fill(0);
const mappedArray = originalArray.map((n, index) =>
  Math.floor(Math.random() * 100)
);

console.log("mappedArray", mappedArray);
console.log("joined array string", mappedArray.join(","));

async function callApi(numbers) {
  const fetchResponse = await fetch(`http://numbersapi.com/${numbers}/math`);

  if (fetchResponse.ok) {
    const data = await fetchResponse.json();
    console.log("all good, heres the response", data);
  } else console.log("There was a problem");
}


const Number = async() => {
    const [add, setAdd] = React.useState([]); // <-- valid initial empty state

    React.useEffect(() => {
        callApi(mappedArray).
          then(values => setAdd(values));
      }, []); // <-- invoke on component mount
    
  <div className="container">
    {add.map((newlist, i) => (
      <div className="item" key={i}>
        {newlist}
      </div>
    ))}
  </div>
);

export default Number;
Run Code Online (Sandbox Code Playgroud)

有人可以帮我解决这个问题吗?谢谢

And*_*ndy 6

  1. 你需要保持状态。React 的生命周期非常特殊。所以这里我有一个data状态和一个setData更新它的函数。

  2. 对于 React 函数组件,我们使用useEffect(本质上是旧的componentDidMount类组件)在组件首次安装时加载数据。然后我们可以使用我们现在知道是对象数组的数据来设置状态。

  3. 一旦状态更新,组件就会重新渲染。然后,您可以Object.entries使用键作为键、使用值作为文本源来进行迭代。

function Number() {

  // Initialise the state with an empty array
  const [data, setData] = useState([]);

  // Separate out the function that creates the number array
  function createNumbers() {
    const originalArray = new Array(10).fill(0);
    return originalArray.map(() => Math.floor(Math.random() * 100)).join('');
  }

  useEffect(() => {
    async function getNumbers() {
      try {
        const res = await fetch(`http://numbersapi.com/${createNumbers()}/math`);
        const data = await res.json();

        // Set the new component state using the data
        setData(data);
      } catch (err) {
        console.log(err);
      }
    }
    getNumbers();
  }, []);

  return (
    <div className="container">
      {Object.entries(data).map(([key, value]) => (
        <div className="item" key={key}>
          {value}
         </div>
       ))}
     </div>
   );

};

 export default Number;
Run Code Online (Sandbox Code Playgroud)