【问题标题】:react-native : state not updated inside the componentWillRecivePropsreact-native : 组件WillReciveProps 中的状态未更新
【发布时间】:2017-09-24 12:56:06
【问题描述】:

我正在寻找很多方法来解决这个问题,但没有一个有效,setState 仍然无法在 componentWillReciveProps 方法中工作这是我的代码:

export class Detail extends React.Component
{
  constructor(props)
  {
    super(props);
    this.state = {
      ids: 'ger'
    }
  }

  componentWillReceiveProps(nextProps) {
    this.setState({ ids: nextProps.data }, () => {
          console.log(nextProps.data+"=this id")
      });
  }


  render()
   {
    return (
      <View>
        <Text>{this.state.ids}</Text>
      </View>
    );
  }
}

如果我这样做 console.log(nextProps.data+"=this id") 它可以将我想要更新的 id 返回到 this.state.ids 。但是在渲染中的&lt;Text&gt;{this.state.ids}&lt;/Text&gt; 仍然显示this.state.ids ('ger') 的默认值,意味着this.state.idscomponentWillReceiveProps 中没有更新。

【问题讨论】:

  • 我认为这与您的previous question 有关,可能是由于您的ListView 上的渲染项目上没有key 属性。请看this answer
  • 我试过了,还是会出现这个问题,奇怪的是nextProps.data在我做console.log(nextProps.data+"=this id")的时候成功获取了id(比如输出是“4=this id”)但是ids状态仍然没有更新,即使我已经在componentWillReceiveProps里面做了this.setState({ ids: nextProps.data }):'(

标签: javascript react-native


【解决方案1】:

setState() 并不总是立即更新组件。

你可以在here找到你需要的一切。

实际上正如 react 文档所说“React 在挂载过程中不会调用带有初始 props 的 componentWillReceiveProps。它仅在组件的某些 props 可能更新时才调用此方法。调用 this.setState 通常不会触发 componentWillReceiveProps。”

你可以找到更多here

【讨论】:

    【解决方案2】:

    这在我看来是一种反模式。为什么不直接将 nextProps.data 作为 id 注入到 Detail 组件中?然后你可以像这样直接输出id:

    <Text>{this.props.ids}</Text>
    

    通常您还应该得到一个警告,在“componentWillReceiveProps”中调用 setState 将无效。如果您真的想更新您的状态,我认为可以执行“this.state.ids = nextProps.data”。

    【讨论】:

    • 我相信你设置状态是错误的。查看react docs for using state correctly 了解更多信息。
    • 我知道,用 this.state.something = ... 设置状态会设置状态,但不会重新渲染组件。然而,在 componentWillReceiveProps 之后,组件应该重新渲染,因为 props 发生了变化,除非 shouldComponentUpdate 返回 false。但正如我所说,以这种方式设置状态不是好的做法。
    猜你喜欢
    • 1970-01-01
    • 2020-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-30
    相关资源
    最近更新 更多