React Native子组件未从父级接收更新状态

时间:2018-05-31 21:56:49

标签: javascript reactjs react-native state

我正在尝试实现用户输入用户名和密码的应用登录屏幕,应用程序将检索要存储在应用程序状态的Json Web令牌,以便在服务器上管理其帐户。现在,我的App.js看起来像下面的

const RootStack = StackNavigator(
{
  LoginPage:{screen:LoginPage},
  HomePage:{screen:HomePage},
},
{headerMode:'none'},
);

export default class App extends Component{
constructor(props) {
    super(props);
    this.state = {token:'not available yet'}
}


updateState = async(u,p) => {
    try {
        let token = await this.getToken(u,p);
        let merchantInfo = await this.getMerchantInfo(token);

        this.state = {token: token, merchantInfo}
        console.log(this.state)
        console.log('our token state is '+ this.state.token)
        console.log("our merchantinfo state is "+this.state.merchantInfo.name)
    }
    catch (error) {console.log(error);}
}



// update the state of merchant using authToken
getMerchantInfo = async(authToken) => {
    var options = {
      "method": "GET",
      "headers": {
        "authorization": "Bearer " + authToken,
        "content-type": "application/json"
        }
    }

    try {
        let response = await fetch('http://example.com/merchants/',options);
        let responseJson = await response.json();
        return responseJson;
    } catch (error) {console.error(error);}
}

// send over the username and password to server to retrieve an authToken
getToken = async(u,p) => {
    console.log('username is: '+u+' password is: '+p)
    var options = {
        "method": "POST",
        "headers": {
            "content-type": "application/json"
        },
        "body": JSON.stringify({
            "email": u,
            "password": p,
        }),
    };

    try {
        let response = await fetch('http://example.com/merchants/login',options);
        let responseJson = await response.json();
        return responseJson.token;
    } catch (error) {console.error(error);}
}


render() {
    return (<RootStack screenProps= {this.state} />)
}
}

和我的HomePage.js看起来如下

export default class HomePage extends Component {
constructor(props) {
super(props);
this.state = {isReady: false};
console.log ('HomePage gets this token state: ' + this.props.screenProps.token)
}


render() {
return (
  <Container>
    <Header hasTabs>
      <Left />
      <Body>
        <Title>my app</Title>
      </Body>
      <Right>
        <Button transparent onPress={() => this.props.navigation.navigate('LoginPage')}>
          <Text>Logout</Text>
        </Button>
      </Right>
    </Header>

    <Tabs>
      <Tab heading="Issue">
        <IssueTab />
      </Tab>
      <Tab heading="Redeem">
        <RedeemTab />
      </Tab>
      <Tab heading="Settings">
        <SettingsTab />
      </Tab>
    </Tabs>
  </Container>
);
}
}

当我在App.js中调用console.log(this.state.token)时,我从服务器获取了正确的JWT令牌:

our token state is ayJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.fgJuYW3lIjoibG92ZXNoYWNrIiwiZW1haWwiOiJhQGIuY29tIiwiaW1hZ2UiOiJ4cGxvYWRzL0RlZmF1bHQucG8vIiwibWVyY2hhbnLJZCI6IjViMDBjZGZlNzMwODA4NmE0YjZiOWM3NSIsImlhdCI6MTUyNzgwMjU1MywiZXhwIjoxNTU5MzYwMTUzfQ.0QQStfMyDcmYeqeFToei5M4Q35dj43S05NiI0uosXTg

然而,当我在HomePage.js中的console.log(this.props.screenProps.token)时,我得到了初始状态:

HomePage gets this token state: not available yet

我已经尝试过componentWillReceiveProps以及其他一些在这里进行搜索的方法,但对我的情况没有任何作用。在我的情况下如何从HomePage.js中获取App.js的更新状态?

这是我在StackOverflow上的第一篇文章。欢呼并提前致谢!

1 个答案:

答案 0 :(得分:0)

状态只能在构造函数中直接设置,如this.state = { some: 'state' }。在构造函数之外,您必须通过setter this.setStatesetState触发重新渲染,新状态将按预期传递下来。请参阅州文档here

...
 updateState = async(u,p) => {
        try {
            let token = await this.getToken(u,p);
            let merchantInfo = await this.getMerchantInfo(token);

            this.setState({token: token, merchantInfo})
        }
        catch (error) {console.log(error);}
    }
...