简体   繁体   中英

react-native : cant add props to component

im working on simple program. I have List.js and Detail.js and i want to get List.js state in Detail.js using Props but not working (props returns nothing). I tried this but still not working. This is what i did so far :

List.js :

import {Detail} from './Detail';
.
.
.
.
GetItem (nama,id) {
  this.setState({id: id});
  return this.props.navigation.navigate('detail');
}
.
.
.
.
render() {
    if (this.state.isLoading) {
      return (
        <View style={{flex: 1, paddingTop: 20}}>
          <ActivityIndicator />
        </View>
      );
    }

    return (

      <View style={styles.MainContainer}>
      <View><TextInput style={{height: 40,width: 300, marginTop:10}}
      onChangeText={this.onKeyChanges.bind(this)}
      />
      </View>
        <View><ListView
          dataSource={this.state.dataSource}
          renderSeparator= {this.ListViewItemSeparator}
          renderRow={(rowData) => <Text style={styles.rowViewContainer}
          onPress={this.GetItem.bind(this, rowData.nama,rowData.id)} >{rowData.nama}</Text>}
        />
        </View>
      <Detail data={this.state.id}/>
      </View>
    );
}

Detail.js

export class Detail extends React.Component
{
  constructor(props)
  {
    super(props);
    this.state = {
      id: props.data
    }
  }

  componentWillUpdate(nextProps, nextState) {
        nextState.id = nextProps.data;
    }

  render() {
    return <Text>{this.state.id}</Text>;
  }
}

the <Text>{this.state.id}</Text>; shows nothing

You need to change this,

GetItem (nama,id) {
  this.setState({id: id});
  return this.props.navigation.navigate('detail');
}

to this

// setState is asynchronous
GetItem (nama,id) {
  this.setState({id: id}, () => {
    this.props.navigation.navigate('detail');
  });
}

And you need to get new prop on Details component and update the state. There is a really good answer for Why you shouldn't modify state directly

componentWillReceiveProps(nextProps) {
  this.setState({ id: nextProps.data });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM