首页 > 解决方案 > React Native 状态变量未从道具更新

问题描述

我将 3 个道具 - numLikes、id 和 userLiked 传递给我的班级,我想在任何渲染发生之前首先设置我的状态变量。理想情况下,状态变量的值应该等于它们的 props 对应值,但事实并非如此。

这是我的代码:

export default class LikeButton2 extends Component {
  constructor(props) {
    super(props);
    this.state = {
      numLikes: props.numLikes,
      id: props.id,
      userLiked: props.userLiked,
      isloading: true,
    };
  }
 //....
}

我使用 React Native Debugger 检查变量值,变量“numLikes”和“userLiked”没有得到更新。附上相同的证明:

在此处输入图像描述

我也尝试使用传播语法。这是我的代码:

export default class LikeButton2 extends Component {
  constructor(props) {
    super(props);
    this.state = {
      ...props,
      isLoading: true,
    };
  }
 //....
}

尽管这也导致状态变量的值不理想。RN Debugger 中的证明:

React Native 调试器输出 - 2

如何正确更新值?

标签: reactjsreact-native

解决方案


在这个例子中,当组件被挂载显示时,状态被设置为等于props。构造函数只在那个时候被调用。

之后,如果道具发生变化,状态将不会更新以匹配它们。如果您希望在道具更改时更新您的状态,则需要使用方法ComponentDidUpdate : ComponentDidUpdate(prevProps,prevState)

每次道具或状态发生变化时都会调用它。然后,您可以比较当前的 props (this.props) 和以前的 props (prevProps) 以相应地设置您的状态。

如果您只想按原样使用您的道具,您可以直接使用this.props,它将始终反映您赋予组件的价值。

如果<Component number={myNumber}/>代码中有某处,则每次 myNumber 更改时,Component 都会重新渲染,并且this.props.myNumberComponent 中的值将是准确的。

export default class ComponentTest extends Component {
  constructor(props) {
    super(props);
  }
  render() {
     return <div>{this.props.number}</div>
  }
}

推荐阅读