首页 > 解决方案 > 从 React Native 和 Redux 中的嵌套子元素更新父属性

问题描述

我在父组件和子组件之间存在通信问题。我知道不建议修改子级别的专业人士,我也知道可以通过在父组件上执行的调用回调函数。

所以这里有更多关于实现的细节:

1 - 我有一个SearchScreen 带有搜索按钮的搜索屏幕,它调度调用 API 的 Redux 操作,在得到结果后我们导航到第二个屏幕ResultScreen

  class SearchScreen extends Component {
      constructor(props) {
        super(props);
        this.state = {
          immatriculation: '',
        };
      }
      confirmer = () => {
        if (this.state.immatriculation) {
          let action = searchAction.requestFindByImm({
            type: Constants.SEARCH_BY_IMM,
            value: {
              cmd: 'findByImm',
              data: {
                numero: this.state.immatriculation
              },
            },
          });
          this.props.navigation.navigate('ResultScreen', {
            first: true,
          });
          this.props.dispatch(action);
        }
      };
      render() {
        return (
          <View>
            <ScrollView
              horizontal={false}
              ref={(ref) => {
                this.scrollViewRef = ref;
              }}
              onLayout={(event) => {
                this.layout = event.nativeEvent.layout;
              }}>
              <Row>
                <Col size={2}>
                  <Text>
                   Immatriculation
                  </Text>
                </Col>
                <Col size={4}>
                  <TextInput
                    mode="outlined"
                    value={this.state.immatriculation}
                    onChangeText={(text) =>
                      this.setState({immatriculation: text})
                    }
                  />
                </Col>
              </Row>
              <Divider />
              <Button
                onPress={this.confirm}
                icon="check"
                compact="true"
                mode="contained">
                {translate('confirm')}
              </Button>
            </ScrollView>
          </View>
        );
      }
    }
    
    const mapStateToProps = (state) => ({
      ...state.searchReducer,
    });
    
    export default connect(
      mapStateToProps,
      null,
    )(SearchScreen);

mapStateToProps2 - 我通过包含嵌套组件 ( ) 的第二个屏幕捕获结果,ResultScreen -> Comp1->...并将接收到的参数传递mapStateToProps 给子组件。

class ResultScreen extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      errorMsg: '',
     name: '',
    };
  render() {
    return (
      <View>
        <ScrollView
          horizontal={false}
          ref={(ref) => {
            this.scrollViewRef = ref;
          }}
          onLayout={(event) => {
            this.layout = event.nativeEvent.layout;
          }}>
          <Grid>
            <Row >
              <Col size={2}>
                <TextInput
                  mode={'outlined'}
                  value={
                    this.props.data.name
                  }
                  label={translate('name')}
                  onChangeText={(text) =>
                    this.setState({
                      name: text,
                    })
                  }
                />
              </Col>
     ......
     
          
            </Row>
          </Grid>
          <Comp1 datainfo={this.props.data.listeinfo} />
        </ScrollView>
      </View>
    );
  }
}
function mapStateToProps(state) {
  return {...state.searchReducer};
}

export default connect(
  mapStateToProps,
  null,
)(ResultScreen);

因此,在子组件上Comp1,我需要对 props ( props.datainfo) 进行更改,因为我有一个输入可以将项目添加到我收到的列表中,以及我阻止的位置。

export default class Comp1 extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      listeInfo: [],
      newinfo: "",
      selectedItem: "",
    };
  }
  static getDerivedStateFromProps(props, state) {
    if (props.datainfo !== state.listeInfo) {
      return {
        listeInfo: props.datainfo,
      };
    }
    return null;
  }

  add = () => {
    this.setState({listeInfo: [...this.state.listeInfo, this.state.newinfo]})
  };


  renderItem = ({item}) => {
    return (
      <View >
        <TouchableOpacity
          onPress={() =>
            this.setState({
              selectedItem: item,
            })
          }>
          <Text>{item}</Text>
        </TouchableOpacity>
      </View>
    );
  };
  render() {
    const {listeInfo, newinfo} = this.state;

    return (
 
            <Row>
              <Col>
                <infoTextInput
                  value={newinfo}
                  label={translate(info)}
                  onChangeText={(text) =>
                          this.setState({newinfo: text})
                        }
                />
              </Col>
            <Col>
                <Button onPress={this.add}>
                    {translate('add')}
                  </Button>
              </Col>

              <Col >
                <SafeAreaView >
                    <FlatList
                      data={listeInfo}
                      renderItem={(item) => this.renderItem(item)}
                      keyExtractor={(item) => item}
                      nestedScrollEnabled={true}
                    />
                </SafeAreaView>
              </Col>
            </Row>
    );
  }
}

有什么建议么?

标签: reactjsreact-nativereduxreact-propslifecycle

解决方案


推荐阅读