【发布时间】:2019-03-14 17:54:09
【问题描述】:
今天我来找你是因为我在构建应用程序时遇到了一些问题, 我要做的是在父状态更新时更新我的组件状态,我已经尝试从那里选择解决方案,但它们都不起作用
这是我的子组件的样子:
class SideBarSimu extends component{
constructor(props){
this.state = {
addedConfigs: { },
// should looks like { key1: { property1: {} , property2: {}}, ... }
cached: { },
// used to compare the addedConfig[key] im editing with the new prop
editing: null, // the addedConfig key im currently edting
...
}
}
// here i put the methods im trying
...
render(){
...
}
}
这是我迄今为止尝试过的事情:
componentWillReceiveProps(nextProps){
console.log(this.state.cached)
console.log(nextProps.moduleDetails)
if(nextProps.moduleDetails !== this.props.moduleDetails && this.state.editing !== null){
let temp = this.props.getModules() // returns the parent's state i need to store into this.state.addedConfigs[key], can't use this.props because i need to add extra keys
let configs = {...this.state.addedConfigs}
configs[this.state.editing] = temp
this.setState({ addedConfigs: configs })
}
}
这根本不起作用,所以我尝试了:
static getDerivedStateFromProps (nextProps, prevState) {
if(nextProps.moduleDetails !== prevState.cached && prevState.editing !== null) {
let temp = nextProps.getModules()
let config = {...prevState.addedConfigs}
config[prevState.editing] = temp
return {
addedConfigs: config,
cached: nextProps.moduleDetails
};
} else {
return null
}
}
这是我尝试的最后一件事:
shouldComponentUpdate(nextProps, nextState){
if(nextProps.moduleDetails !== nextState.cached && nextState.editing !== null){
let temp = this.props.getModules()
let config = {...nextState.addedConfigs}
config[nextState.editing] = temp
this.setState({ addedConfigs: config, cached: nextProps.moduleDetails })
}
return true
}
在我第一次分配 this.state.editing 时,它确实有效,但是当我对父母状态进行更改时,它不会验证 if 语句,所以我想我可能会误解那里的某些东西
任何帮助将不胜感激
【问题讨论】:
-
componentWill...方法现在被componentDid...方法取代 -
我不明白
addedConfigs = { },为什么不addedConfigs: { },? -
如果你想强制更新??使用
this.forceUpdate()此处 docs facebook.github.io/react/docs/component-api.html 或尝试从 setState 回调,类似this.setState({ key: value }, function() { // callbak -> this.state is updated }); -
Sterling Archer:我会试试的,不知道 Stever:我的错误我已经更新了,我应该复制/粘贴但我的组件中有很多不相关的东西 Jorge Felix Cazarez:我'从未听说过 this.forceUpdate,我会调查一下
标签: reactjs state react-props