Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/cmake/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 使用componentwillreceiveprops设置初始状态?_Reactjs_Components_Flux - Fatal编程技术网

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将包含传入的值。