从反应js的道具更新ui。响应中的道具状态切换

时间:2016-12-20 00:05:25

标签: reactjs redux state

当我在reactjs和redux构建中更改道具时,我无法弄清楚如何更新我的UI。这似乎是一个相对正常和简单的问题,但我正在努力解决它。我发现围绕这个做出反应的文件严重不足https://facebook.github.io/react/docs/react-component.html#componentwillreceiveprops(一个段落有一个简短的解释而没有例子)。我还希望以新的和正确的es6格式看到这一点。 根据我的理解,我可以设置我的道具并绑定它们,以便更新我的状态。我设置了初始道具,因此请求的道具永远不会为空。我为状态做了同样的事情,它没有出现在渲染或我的状态树中。

我发现这是为了设置我的初始状态并使用它

export default class MyComponent extends React.Component{
  constructor(props){
    super(props);
    this.state = { userBirthdate: '1/2/1982', };
  }
}

我发现这是为了使用componentWillReceiveProps()

更新ui
componentWillReceiveProps(nextProps) {
  this.setState({
    userBirthdate: nextProps.userBirthdate
  });
}

但是,当我查看反应检查员时,我的容器没有状态(在状态下的检查员中显示"空对象"的消息)。道具正在更新并反映我在redux中的用户选择。当我选择一个新元素时,它会反映在redux中,填充我正在使用的正确道具,但它们不会传递到状态。

对此的任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

看起来生命周期函数shouldComponentUpdate将成为您的选择

export default class MyComponent extends React.Component{
  constructor(props){
    super(props);
    this.state = { userBirthdate: '1/2/1982', };
  }
  shouldComponentUpdate(nextProps, nextState) {
    if(this.props.userBirthdate !== nextProps.userBithdate) {
       return true;
    }
  }
}

答案 1 :(得分:0)

如果所需数据是通过道具传入的,请不要担心"同步"除非你需要在组件中操作它,否则它要声明。

相反,只需直接使用道具,例如:

export default class MyComponent extends React.Component{

  static defaultProps = {
    userBirthdate: '1/2/1982'
  };

  render() {
    const { userBirthdate } = this.props;
    return <span>DOB: {userBirthdate}</span>;
  }
}
相关问题