我从“数字组件”向“主组件”发送数值。一切都很顺利,直到我将该值设置为该组件的状态。
var Numbers = React.createClass({
handleClick: function(number){
this.props.num(number)
},
render: function(){
return (
<div>
<button onClick={this.handleClick.bind(null, 1)}>1</button>
<button onClick={this.handleClick.bind(null, 2)}>2</button>
<button onClick={this.handleClick.bind(null, 3)}>3</button>
</div>
)
}
})
var Main = React.createClass({
getInitialState: function(){
return {
number: 0
}
},
handleCallback: function(num){
console.log("number is right here: " + num);
this.setState({
number: num
})
console.log("but wrong here (previous number): " + this.state.number)
},
render: function() {
return (
<Numbers num={this.handleCallback} />
//<SomeComponent number={this.state.number} />
)
}
});
React.render(<Main />, document.getElementById('container'));
为什么它会表现成这样?handleCallback
函数中的第二个console.log
打印了先前的数字,而不是在num
参数中的数字。我需要正确的数字在我的状态中,因为我将立即将其作为属性发送到我的SomeComponent
组件。
SomeComponent
的问题?我现在知道它为什么不起作用,但我不知道如何在仅当this.state
已更新时将状态作为 props 传递。我能否以某种方式将<SomeComponent number={this.state.number} />
包装到回调函数或其他东西中? - StrangeManInMaskshouldComponentUpdate
来告诉它不要这样做。因此,一旦在<Main/>
中更改了状态,它将重新渲染,并将新数字作为新属性传递给<SomeComponent/>
。如果您在<SomeComponent/>
中实现了componentWillReceiveProps
,则会在接收到的属性中看到该数字。这有意义吗?还是您希望我修改我的答案并深入一点? - Michael Parker<SomeComponent/>
不等待<Main/>
重新渲染(我认为..),因此无法发送状态的正确值。我不知道如何实现您展示的回调函数。也许这可以更好地解释:https://jsfiddle.net/69z2wepo/13007/ - StrangeManInMask<SomeComponent/>
中的当前props而不是新的props。函数componentWillReceiveProps
可以接受一个参数nextProps
,其中包含所有接收到的新props。这是修复后的版本:https://jsfiddle.net/69z2wepo/13008/。只需记住,在`componentWillReceiveProps`执行完成之前,`this.props`不会改变。 - Michael Parker