当行是具有它自己状态的组件时,反应本机列表视图不会更新

时间:2017-04-04 12:28:18

标签: listview react-native

以下是我主要内容的简化摘要:

// this is only to simulate a change
componentDidMount() {
  setTimeout( () => {
    this.setState({
       dataSource: this.state.dataSource.cloneWithRows([ newVehicle ]),
    })
  }, 5000)
}

render() {
 return (
  <ListView
    dataSource={this.state.dataSource}
    renderRow={this.renderVehicle}
  />
 )
}

renderVehicle(vehicle) {
  // here vehicle.name is properly updated
  return <Text>{vehicle.name}</Text> // this would be working
  return <Vehicle parentObject={ vehicle } /> // this is not working
}

这是我的车辆组件:

// In here it seams the component is not rebuilt,
// and this.props.parentObject is always the old value...

this.state = this.props.parentObject

return() {
  <Text>{this.state.name}</Text>
}

注意:在现实生活中,车辆是一个复杂的组件,需要拥有自己的状态。

1 个答案:

答案 0 :(得分:1)

据我所知,您需要在车辆中使用componentWillReceiveProps(nextProps:Object)并使用 nextProps 更新状态。

简单示例:

componentWillReceiveProps(nextProps) {
  const { name } = nextProps;

  this.setState({name});
}