簡體   English   中英

React Native子組件未從父組件接收更新狀態

[英]React Native child component does not receive updated state from parent

我正在嘗試實現一個應用程序登錄屏幕,在該屏幕上,用戶輸入用戶名和密碼,並且該應用程序將檢索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上的第一篇文章。 預先加油,謝謝!

狀態只能在構造函數內部直接設置,例如this.state = { some: 'state' } 在構造函數之外,您必須通過設置程序this.setState setState觸發重新渲染,新狀態將按預期傳遞。 請在此處查看狀態文檔。

...
 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);}
    }
...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM