【问题标题】:State change not reflecting on the UI of child component状态变化不反映子组件的 UI
【发布时间】:2019-10-15 21:01:17
【问题描述】:

我有两个组件 FirstParentSecondParent 他们都有相同的子组件 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 };
);

子组件

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,
    )
  )
);

【问题讨论】:

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


    【解决方案1】:

    我能够让第二个组件通过改变事物来反映状态的变化。但我仍然不满意,因为现在我必须遍历状态来检索项目。

    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} />
    }
    

    子组件

    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,
        )
      )
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-12
      • 2021-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-26
      • 2018-09-23
      • 2022-01-19
      相关资源
      最近更新 更多