Reactjs 使用componentwillreceiveprops设置初始状态?
我正在写一个图像组件,并且被困在组件上将收到道具 以下是组件的要点Reactjs 使用componentwillreceiveprops设置初始状态?,reactjs,components,flux,Reactjs,Components,Flux,我正在写一个图像组件,并且被困在组件上将收到道具 以下是组件的要点 class ImageField extends React.Component { constructor(props) { super(props); this.state = { image: '', imagePreviewUrl: '', }; } componentWillReceiveProps(newProps){ if (newProps.content === this.p
class ImageField extends React.Component {
constructor(props) {
super(props);
this.state = {
image: '',
imagePreviewUrl: '',
};
}
componentWillReceiveProps(newProps){
if (newProps.content === this.props.content) {
return;
}
this.setState({
image: this.props.content
}, function() {
console.log(this.state.image)
})
}
我有一个react表单,它向ImageField组件发送一个json块,当componentWillReceiveProps触发时,应该将this.state.image设置为该json块
然而,它从不设置它,当它点击console.log时,它返回未定义的this.state.image
现在,如果我两次执行this.setState,它会将json写入this.state.image,但我不想这样做,因为这样做可能是错误的
卡住了,正确的方法是什么?首先,您需要初始化构造函数中的状态,如下所示,因为当最初创建组件时,不会调用
组件willreceiveprops()
,而是使用初始的props调用构造函数
constructor(props) {
super(props);
this.state = {
image: props.content,
imagePreviewUrl: '',
};
}
接下来修改组件将接收props()
,如下所示,以便使用newProps
调用setState()
componentWillReceiveProps(newProps){
if (newProps.content === this.props.content) {
return;
}
this.setState({
image: newProps.content
}, function() {
console.log(this.state.image)
})
}
它不应该是
this.setState({image:newProps.content},…})
?您正在使用this.props进行设置,它在component中设置之前未定义。它将接收props
。您不希望setState中包含this.newProps.content吗?newProps将包含传入的值。