【发布时间】:2019-03-18 15:40:46
【问题描述】:
在触发位于渲染中的函数 (filterAndSort) 之前,面临状态未更新的问题。我在函数中添加了一个 console.log 语句,并且只有一个状态得到更新。我的代码对我来说似乎是合乎逻辑的,因为我设置了一个 if 条件,其中只有在 setState 发生后才会触发函数
完整的错误信息:
警告:无法在未安装的设备上调用 setState(或 forceUpdate) 零件。这是一个无操作,但它表明您的内存泄漏 应用。要修复,请取消所有订阅和异步任务 在 componentWillUnmount 方法中。
但是,我怀疑这是因为我有多个 setStates 异步发生。
我在想,也许,只有在获取所有 axios 请求后,我才需要为所有变量重写 componendDidMount 到 setState。 Multiple Axios Requests Into ReactJS State
我认为另一种解决方案是将函数的返回结果存储为状态而不是变量,然后添加 componentDidUpdate。
componentDidUpdate(prevProps, prevState) {
if (this.state.value > prevState.value) {
this.filterAndSort();
}
}
组件
class Results extends Component {
constructor(){
super()
this.state = {
results: [],
races: [],
arr = []
isLoading: true
};
}
componentDidMount(){
const oneRequest = axios.get(URL_ONE)
.then(response =>
response.data.data.map(result => ({...
))
)
.then(results => this.setState({results, isLoading: false}))
const twoRequest = axios.get(URL_TWO)
.then(response =>
response.data.data.map(race => ({...}))
)
.then(races => this.setDefault(races))
}
setDefault = (races) => {
........
this.setState({arr, races, isLoading:false})
}
filterAndSort = (races, results) => {
console.log(races, results)
.......
}
render() {
const{races, results} = this.state
if (isLoading == true) {
return (
<div>
<p>Loading...</p>
</div>
)
} else {
return (
<div>
<BarChart
qualData={this.filterAndSort(races, results)}
raceData={this.filterAndSort(races, results)}
width="1200"
height="500" />
</div>
);
}
}
}
export default Results;
【问题讨论】:
标签: javascript reactjs