React Native:将responsejson传递给其他屏幕

时间:2019-12-05 14:19:17

标签: reactjs react-native

我想将 LoginActivity 类中 UserLoginFunction 函数的响应数据带入 ProfileActivity 类中,然后将其发送到 routes.js 。但是有一条错误消息,如下所示:

enter image description here

import Routes from './routes';

class LoginActivity extends Component {
    constructor(props) {
        super(props)
        this.state = { dataSource: [] }
    }

    UserLoginFunction = () =>{

        fetch('https://example/login.php', { 
            ....
        })
        .then((response) => response.json())
        .then((responseJson) => {
            this.setState({
                dataSource: responseJson
            });
            this.props.navigation.push('Second', {ds: this.state.dataSource});
        })
        .catch((error) => {
            ...
        });
    }
    render() {
        return (
            <View ...
                ...
                <TouchableOpacity onPress={this.UserLoginFunction} style={styles.button}>
                    <Text style={styles.buttonText}>LOGIN</Text>
                </TouchableOpacity>     
            </View>
        );
    }
}


class ProfileActivity extends Component {
    render(){
        const { navigation } = this.props;
        return(
            this.props.navigation.push('Routes', {dataSource: this.props.navigation});
        );
    }
}


export default MainProject = createAppContainer(createStackNavigator( {
    First: { screen: LoginActivity, },
    Second: { screen: ProfileActivity, }
}));

请帮助我,谢谢

1 个答案:

答案 0 :(得分:0)

您可以使用状态来过滤来自第一个屏幕的响应,以便您通过它

但是在第二个屏幕中,您应该这样做

class ProfileActivity extends Component {
  constructor(props){
     super(props);
     this.state = {
        response: this.props.navigation.getParam('ds')
     }
 }

  render(){
          const { response } = this.state;
          return(
              this.props.navigation.push('Routes', {dataSource: response})
          );
      }
  }