我有两个函数,一个从api提取数据并根据该数据更新状态,另一个函数在状态中的数据上进行迭代并用新数据更新状态。
我的问题是我无法更新第二个功能的状态。而且我不知道我必须在哪里调用此函数才能在第一个函数之后调用它并使用状态中的数据多数民众赞成在。
export default class Cases extends Component {
constructor(props) {
super(props);
this.state = {
cases: [],
photos: [],
};
this.addPhotos = this.addPhotos.bind(this);
this.getCases = this.getCases.bind(this);
this.renderCases = this.renderCases.bind(this);
}
getCases() {
axios
.get('/cases/api')
.then(response => {
this.setState({
cases: response.data.cases,
photos: response.data.photos,
});
console.log(this.state.cases);
})
.catch((error) => {
if (error) {
console.log(error);
}
});
}
addPhotos() {
const newCases = this.state.cases.map(({ photo_id, ...rest }) => {
const obj = { ...rest };
this.state.photos.find(data => {
if (data.id === photo_id) {
obj.file = data.file;
return true;
}
});
return obj;
});
console.log(this.state.cases);
this.setState({
'cases' : newCases
});
}
renderCases() {
this.addPhotos();
}
componentWillMount() {
this.getCases();
}
render() {
return (
<div>
{this.renderCases()}
</div>
)
}
}
这就是我现在所拥有的
我应该在哪里调用addPhotos函数,以便它可以更新状态并仍然使用getCases函数中的现有状态数据?
提前致谢!
相关分类