这是我的代码。就像我尝试构建组件文章时一样,它所提供的值也是如此。我收到错误说明错误:对象作为React子对象无效(找到:带有键{articles}的对象)。如果要渲染子级集合,请改用数组。
即使文章中的值是对象数组,映射时也会引发此错误。我应该在此组件中导入任何内容,否则代码中是否有错误。这是在控制台中打印文章值时的图像- > enter image description here
import axios from 'axios';
import Article from './Article'
class Articles extends Component {
state = {
articles: [],
}
componentDidMount () {
axios.get('https://jsonplaceholder.typicode.com/posts')
.then(response => {
console.log(response);
this.setState({articles: response.data});
});
}
render () {
let articles = this.state.articles.map(article => {
return <Article />;
});
return (
{articles}
);
};
};
export default Articles;
最佳答案
您将JavaScript对象的花括号和JSX的花括号弄混了。
当您返回{ articles }
时,实际上是在返回一个对象,该对象具有一个名为articles
的键,并将Article
的列表作为值。
等效于:
render () {
const list = this.state.articles.map(article => {
return <Article />;
});
return (
{articles: list}
);
};
您只需要返回
articles
即可:render () {
const articles = this.state.articles.map(article => {
return <Article />;
});
return articles;
};
如果在JSX中使用了
articles
,则在articles
周围使用花括号将是正确的:render () {
const articles = this.state.articles.map(article => {
return <Article />;
});
return (
<>{articles}</>
);
};
关于arrays - 错误: Objects are not valid as a React child (found: object with keys {articles}),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58651883/