I am working on an app it have an array of data User selects timeSpan like monthly
, weekly
etc according to that array should be rendered on screen. I tried doing this in componentWillUpdate
which i am not sure. But it gave me error.
There is a dropdown from where user selects timespan
value. I don't know where should i put this so that it listen for changes in timeSpan
Any Help would be great
Here is my code.
if (this.state.timeSpan === "yearly") {
const yearlyData = this.props.dispensingData.duration["yearly"];
this.setState({ spanData: yearlyData });
} else if (this.state.timeSpan === "weekly") {
const weeklyData = this.props.dispensingData.duration["weekly"];
this.setState({ spanData: weeklyData });
}
You don't need to use setState
to pick a particular key from a prop. You should use setState
for data that's eg user-entered.
const {timeSpan} = this.state;
let data;
if (timeSpan === "yearly" || timeSpan === "weekly") {
data = this.props.dispensingData.duration[timeSpan];
}
in eg your render function should be enough for this usecase.
You can use the componentDidUpdate method (docs here: https://fr.reactjs.org/docs/react-component.html#componentdidupdate ),
componentDidUpdate(prevProps, prevState) {
if (prevState.timespan !== this.state.timespan) {
if (this.state.timeSpan === "yearly") {
const yearlyData = this.props.dispensingData.duration["yearly"];
this.setState({ spanData: yearlyData });
} else if (this.state.timeSpan === "weekly") {
const weeklyData = this.props.dispensingData.duration["weekly"];
this.setState({ spanData: weeklyData });
}
}
}
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.