简体   繁体   English

无法将状态传递给另一个组件[react-native]

[英]Can't pass state to another component [react-native]

I am trying to send request to api, and save one of the parameters I get from there inside my state, and then send it to another component to be used. 我试图将请求发送到api,并将从那里获取的参数之一保存在我的状态内,然后将其发送到另一个要使用的组件。

getCode function to send request, class method getCode函数发送请求,类方法

getCode(text, psw) {
fetch('someurl', {
  method: 'POST',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json'
  },
    body: JSON.stringify({"telephone": text, "password": psw})
  })
  .then(response => response.json())
  .then(response => {
    //console.log(this.state.text) console.log(this.state.uid)

    this.setState({uid: response["data"]["id"]
    })
    console.log(this.state.uid)
    // this.setState({uid: response["data"]["telephone"]})
    // console.log(this.state.uid);
  })
  }

Button which runs getcode function and navigates to another screen/component where I want to send my state 运行getcode函数并导航到我要发送状态的另一个屏幕/组件的按钮

<Button
      title="do it"
      onPress=
      {() => {this.props.navigation.navigate('SecondPage', {uid: this.state.uid}), this.getCode(this.state.text, this.state.password)} }/>
  </View>

Here is my constructor and state of sender component 这是我的构造函数和发送方组件的状态

constructor(props) {
super(props);
this.state = {
  text: '',
  password: '',
  password2: '',
  uid: ''
}
}

Here is constructor and state of second component 这是第二个组件的构造函数和状态

constructor(props) {
    super(props);
    this.state = {
      value: "",
      focused: false,
      text: "",
      u_id: this.props.navigation.state.params.uid,
    };
  }

So the question is how do I send state to another component? 所以问题是如何将状态发送到另一个组件? tried couple tutorial but not working for me. 尝试了几个教程,但不适用于我。 And should I use props instead of state, since they are public? 而且由于道具是公共的,我应该使用道具而不是状态吗? Please feel free to give advices on logic and code overall 请随时就整体逻辑和代码提出建议

Looking at the code in your button, it seems strange that you are calling the function to get the code after you have navigated to the next screen. 查看按钮中的代码,在导航到下一个屏幕后调用函数以获取代码似乎很奇怪。

<Button
  title="do it"
  onPress=
    {() => {
      this.props.navigation.navigate('SecondPage', { uid: this.state.uid });
      this.getCode(this.state.text, this.state.password);
    }}/>

Calling the function that gets your code after you navigate means that your uid value will not have updated. 导航后调用获取代码的函数意味着您的uid值将不会更新。

If you want to get the code then pass the code to the next screen I would imagine that you should be doing something like this: 如果您想获取代码,则将代码传递到下一个屏幕,我想您应该执行以下操作:

getCode = (text, psw) => {
  fetch('someurl', {
    method: 'POST',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ 'telephone': text, 'password': psw })
  })
    .then(response => response.json())
    .then(response => {
      let uid = response['data']['id'];
      // this is the correct way to check a value after you have set it to state
      this.setState({ uid }, () => console.log(this.state.uid));

      // now that we have got the code we should navigate to the next screen
      // passing the uid as a parameter
      this.props.navigation.navigate('SecondPage', { uid });
    });
}

I would then change the code in the onPress of your button to 然后,我将在按钮的onPress中将代码更改为

<Button
  title="do it"
  onPress=
    {() => {
      this.getCode(this.state.text, this.state.password);
    }}/>

Then you should be able to access the value in the next screen by using this.props.navigation.state.params.uid 然后,您应该可以使用this.props.navigation.state.params.uid在下一个屏幕中访问该值

You cannot send state from one component to another, but they can share one instance of state if you pass the state to both of them through props. 您无法将状态从一个组件发送到另一个组件,但是如果您通过道具将状态传递给两个组件,则它们可以共享一个状态实例。 If you want you can dive in Redux - State management library, which provides single source of state for all components, or the quick solution is that if your components share the same parent than you can lift your state there. 如果您愿意,可以潜入Redux-状态管理库,该库为所有组件提供单一的状态源,或者快速的解决方案是,如果您的组件共享同一父级,则可以在此处提升状态。

Component A is Parent its state is 组件A是父项,其状态是

this.state = {
  uuid: null
}

you create a method which sets this uuid prop for you ie 您创建一个为您设置此uuid属性的方法,即

setUuid = (uuid) => {this.setState({ uuid })}

You have to pass it to your fetch function through props and call it there in then callback like this 您必须通过道具将其传递给fetch函数,然后在其中调用它,然后像这样进行回调

    getCode(text, psw) {
fetch('someurl', {
  method: 'POST',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json'
  },
    body: JSON.stringify({"telephone": text, "password": psw})
  })
  .then(response => response.json())
  .then(response => {
    this.props.setUuid(response["data"]["id"])
  })
  }

This will update the state of the parent and now you can pass this uuid prop from parent to the component where you are using it in your case it is 这将更新父级的状态,现在您可以将这个uuid prop从父级传递到正在使用它的组件(如果是)

<Button
  title="do it"
  onPress=
  {() => {this.props.navigation.navigate('SecondPage', {uuid: this.props.uuid}), this.getCode(this.state.text, this.state.password)} }/>

Also please notice that in onPress prop you reference uuid like uid, in the above code snippet I fixed that for you. 还请注意,在onPress属性中,您像uid一样引用uuid,在上面的代码段中,我已为您修复了该问题。

Why are you navigating to another screen while your fetch is not complete yet? 为什么在提取尚未完成时导航到另一个屏幕? You should either wait for the response to complete, set state, and after state has been set navigate to the next screen, or just pass the required data (telephone and password) to next screen as props and let it call the API itself. 您应该等待完成响应,设置状态, 状态已经被设置后转到下一屏幕,或只是通过所需的数据(电话和密码)到下一个屏幕作为道具,让它调用API本身。

Also you have a bug, this.props.text should be this.state.text 另外你有一个错误,this.props.text应该是this.state.text

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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