在本机反应中渲染子组件而不是父组件

时间:2019-05-19 15:14:49

标签: reactjs react-native

子组件未在父组件的更改中呈现

我有一个带下拉列表的父组件。当下拉列表发生更改时,我需要更新子组件,但不呈现父组件。

const CrewsAdapter = props => {
  let crewName = 'jack nickelson';
  if(props.data.loading) {
    return <View><Text>Loading crews</Text></View>
  }
  if(props.data.getAllCrews) {
      crewsNames= props.data.getAllCrews.map(crew => ({"value": crew.crewName}));
    return (
          <View style={{ flexDirection: 'column', alignItems: 'center', backgroundColor: '#ffffff' }}>
            <View style={[styles.container, { flex: 0.25 }]}>
              <Text style={styles.headerText}>Crews</Text>
            </View>
            <View style={{ flexDirection: 'row' }}>
              <View style={{ flex: 0.9 }}>
                <Dropdown label="Crews List"
                          data={crewsNames}
                          onChangeText = {(value) => {crewName = value}}
                />
              </View>
            </View>
            <View style={{ flexDirection: 'row' }}>
            <Crew crewName={crewName}/>
            </View>
          </View>
    );
  }
  return <View><Text>No data</Text></View>
};

export default class CrewsScreen extends Component {
  constructor(props) {
    super(props);
    this.stateHandler = this.stateHandler.bind(this);
    this.state = {
      crewName: '',
    }
  }

  stateHandler(value){
    this.setState({crewName: value});
    console.log('crewName: ' + this.state.crewName);
  }

  render() {
    const AllCrews = graphql(crewsList, {options: (props => ({}))})(CrewsAdapter);
    return (
        <SafeAreaView style={styles.screen}>
          <ToolBar />
          <AllCrews stateHandler = {this.stateHandler}/>
          <CrewsListFooter navProps={{...this.props}}/>
        </SafeAreaView>
    );
  }
}

当“ Crews List”的值更改时,我需要重新渲染“ Crew”组件,而无需重新渲染父组件,因为下拉列表已通过api调用生成。

下面是Crew组件的构造函数和componentWillRecieveProps功能。

export default class Crew extends Component {
    constructor(props) {
        super(props);
        this.state = {
            crewName: props.crewName
        }
    }
    componentWillReceiveProps({crewName}) {
        this.setState({...this.state,crewName})
    }

1 个答案:

答案 0 :(得分:0)

不幸的是,我认为这是不可能的,因为为了更新Crew组件,必须从父项CrewList传递道具,并且在{ {1}}组件因此触发了React lifecycle

的更改