状态更改未反映在子组件的UI上

时间:2019-05-30 08:14:55

标签: reactjs react-native react-redux redux-thunk

我有两个组件 FirstParent SecondParent ,它们都有相同的子组件 Child

如果在 FirstParent 中单击图标,状态(redux)将更新,并且UI会将Text的值反映为20。

但是,如果我从 SecondParent 中执行相同的操作,则只会更新状态(redux),但UI不会将Text的值显示为20。

我在这里想念什么?

FirstParentComponent

handleRender = ({ item }) => {
  // some code here
  return (
    <Child foo={item} />
  )
}

render() {
  <FlatList
    renderItem={this.handleRender}
    // other attributes
  />
}

SecondParentComponent

render() {
  const { item } = this.props;

  // some code here
  <Child foo={item} />
}

// some code here
const mapStateToProps = (state, ownProps) => (
  const item = state.data.find(
    foo => foo.id === ownProps.navigation.getParam('foo', {}).id)
  )
 return { item };
);

ChildComponent

updateFoo = (id, value) => {
  const { updateReduxState} = this.props;

  // some code here
  updateReduxState({ id, value })
}

render() {
  const { foo: { id, value} } = this.props;

  // some code here
  <Icon onPress={() => { this.updateFoo(id, 20); }}
  <Text>{value}</Text>
}

// some code here
const mapDispatchToProps = dispatch => (
  bindActionCreators(
      { updateReduxState: updateValue},
       dispatch,
    )
  )
);

1 个答案:

答案 0 :(得分:0)

我能够通过改变周围的事物来获得反映状态变化的第二部分。但是我仍然不满意,因为现在我必须遍历状态以检索该项目。

FirstParentComponent

handleRender = ({ item }) => {
  // some code here
  return (
    <Child fooId={item.id} />
  )
}

render() {
  <FlatList
    renderItem={this.handleRender}
    // other attributes
  />
}

SecondParentComponent

render() {
  const { itemId } = this.props;

  // some code here
  <Child fooId={itemId} />
}

ChildComponent

updateFoo = (id, value) => {
  const { updateReduxState} = this.props;

  // some code here
  updateReduxState({ id, value })
}

render() {
  const { foo: { id, value} } = this.props;

  // some code here
  <Icon onPress={() => { this.updateFoo(id, 20); }}
  <Text>{value}</Text>
}

// some code here
const mapStateToProps = (state, ownProps) => (
  const foo = state.data.find(
    foo => foo.id === ownProps.fooId)
  )
 return { foo };
);

const mapDispatchToProps = dispatch => (
  bindActionCreators(
      { updateReduxState: updateValue},
       dispatch,
    )
  )
);