I have an array as a state .
let coursedata=[];
class XYZ extends React.Component {
constructor(props) {
super(props);
this.state = {
coursedata
};
}
componentWillReceiveProps(newProps) {
if (newProps.course.courses.data) {
const newstate = [
...this.state.coursedata,
newProps.courses.courses.data
];
this.setState({
coursedata: newstate
});
}
}
Please not that newProps.course.courses.data is an array of objects. My goal is to have state as an array of objects.
I assume you want to concatenate newProps.course.courses.data
to state.courseData. If that is the case, simple solution would be:
componentWillReceiveProps(newProps) {
const {courseData} = this.state;
if(newProps.course.courses.data) {
return this.setState({
courseData: courseData.concat(newProps.course.courses.data),
});
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.