【发布时间】:2021-09-08 17:51:08
【问题描述】:
我正在学习 React,我正在尝试开发一个代码来从 api“数字 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;
有人可以帮我解决这个问题吗?谢谢
【问题讨论】:
-
newlist是一个对象吗?如果是这样,您不能将其作为子对象传递,如果您想查看整个对象或渲染单个属性,则需要对其进行字符串化。
标签: javascript reactjs