我正在尝试在类之间传递数据,但它不起作用。错误说: “无法读取未定义的属性‘映射’” (我需要它来保持 future 状态的类(class))。 我尝试在不同的组件(不是类)中使用它并且它有效。
这是我的第一个类:
import React, { Component } from 'react';
import ArticlePage from './components/articlePage';
import './App.css';
class App extends Component {
constructor(props) {
super(props);
this.state = {
articles: '',
newArticleList: []
}
}
componentDidMount(){
fetch('https://example.com/wpjson/wp/v2/od_article_embed&page=1&per_page=10')
.then(response => response.json())
.then(myJson => this.setState({articles: myJson.map(articleName => articleName )}))
}
componentDidUpdate(prevProps, prevState) {
if (this.state.articles !== prevState.articles) {
this.setState({newArticleList: this.state.articles.map(article => {
return (
[{image: article._embedded['wp:featuredmedia']['0'].source_url}
)
})})
}
}
render() {
return (
<div className="App">
<ArticlePage
allArticles={this.state.newArticleList}/>
</div>
);
}
}
export default App;
这是我尝试将其转发到的类(class):
import React, {Component} from 'react';
class ArticlePage extends Component {
constructor(props) {
super(props);
this.state = {
}
}
render() {
return (
<div className='articlePage'>
{
this.props.allArticles.map((article,index) => {
return (
<div key={index} className="articlePage__section-content-right-trending">
<img className="articlePage__section-content-right-trending-image" alt="article" src={`${article[0].image}`}/>
</div>
)
})
}
</div>
)
}
}
export default ArticlePage;
最佳答案
在做map之前需要添加条件检查。这里 allArticles 最初是未定义的。另外,关于 key,请尝试在循环中生成 jsx 元素时将数据中的 id 添加为键。如果您没有为数组数据中的每个对象生成唯一的 id,则使用索引作为键,就像我在下面所做的那样
{
this.props.allArticles && this.props.allArticles.map((article,index) => {
return (
<div key={`Key${index}`} className="articlePage__section-content-right-trending">
<img className="articlePage__section-content-right-trending-image" alt="article" src={`${article[0].image}`}/>
</div>
)
})
}
如果你想了解向 jsx 元素添加键的不同方式,可以引用here
关于javascript - 在 React 类之间传递数据不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52547695/