[英]React setState re-render
首先,我真的是React的新手,所以请原谅我对主题的知识不足。
据我所知,当setState一个新值时,它将再次渲染视图(或需要重新渲染的部分视图)。
我有这样的事情,我想知道这是否是一个好习惯,如何解决此类问题以进行改进等。
class MyComponent extends Component {
constructor(props) {
super(props)
this.state = {
key: value
}
this.functionRender = this.functionRender.bind(this)
this.changeValue = this.changeValue.bind(this)
}
functionRender = () => {
if(someParams !== null) {
return <AnotherComponent param={this.state.key} />
}
else {
return "<span>Loading</span>"
}
}
changeValue = (newValue) => {
this.setState({
key: newValue
})
}
render() {
return (<div>... {this.functionRender()} ... <span onClick={() => this.changeValue(otherValue)}>Click me</span></div>)
}
}
另一个组成部分
class AnotherComponent extends Component {
constructor (props) {
super(props)
}
render () {
return (
if (this.props.param === someOptions) {
return <div>Options 1</div>
} else {
return <div>Options 2</div>
}
)
}
}
该代码的目的是,当我单击范围时,它将更改状态的键,然后由于其参数,组件<AnotherComponent />
应该更改。
我保证当我设置setState时,在回调函数上我会抛出一个带有新值的控制台日志,并且它的设置正确,但是AnotherComponent
不会更新,因为根据给定的参数它会显示一件事或另一件事。
也许我需要使用MyComponent的某些生命周期?
编辑
我发现AnotherComponent
接收到的param
没有改变,它始终是相同的。
我建议您首先在changeValue
函数上使用一个简单的console.log
在父级中对其进行测试:
changeValue = (newValue) => {
console.log('newValue before', newValue);
this.setState({
key: newValue
}, ()=> console.log('newValue after', this.state.key))
}
setState
可以接受将在状态实际更改后调用的回调 (请记住setState
是async) 。
因为我们看不到整个组件,所以很难理解那里到底发生了什么。 我怀疑newValue
参数始终是相同的,但我不确定。
好像您在AnotherComponent
的构造函数中缺少了props
。 它应该是:
constructor (props) {
super(props) // here
}
尝试将if语句替换为:
{this.props.param === someOptions? <div>Options 1</div>: <div>Options 2</div>}
还添加此函数以查看新道具是否真正到达组件:
componentWillReceiveProps(newProps){
console.log(newProps);
}
并检查param
和someOptions
的类型,因为(正确地)使用了===
比较。
首先,胖箭头( =>
)自动绑定方法,因此您无需在构造函数中将其绑定,如果更改组件的键,则第二次重新渲染。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.