从一个组件到另一个组件反应本机通过状态

时间:2018-07-03 10:41:18

标签: javascript reactjs react-native

我正在尝试使用react native来创建登录屏幕。

这是我的index.js

export default class LoginScreen extends Component {
  render() {
    return (
      <Wallpaper>
        <Logo />
        <Form />
        <SignupSection />
        <ButtonSubmit />
      </Wallpaper>
    );
  }
}

ButtonSubmit是我使用一些动画创建的自定义按钮。用户单击提交按钮后,我只是不知道如何将表单提交给我的API,因为所有用户输入都被保存为表单组件状态

4 个答案:

答案 0 :(得分:0)

您需要将状态提升到LoginScreen组件中。 Documentation很好地解释了这一点。使用state组件的LoginScreen并将此状态传递到Form组件和onChange组件Form的{​​{1}}更新中的state输入}组件,为此,您可以将回调传递给LoginScreen组件。最后,将回调传递到Form组件,并在按下“提交”按钮时调用它。

答案 1 :(得分:0)

无论哪种方式,您都可以使用redux管理状态。更好的主意是使用redux来管理数据。

您可以阅读本文以了解更多信息。

https://medium.com/@imranhishaam/react-native-with-redux-for-beginners-6281959a2899

答案 2 :(得分:0)

要在状态下传递数据以调用API,则需要设置redux。然后,您可以调用一个动作,在该动作中您将调用API并在化简器中设置API响应。然后可以通过prop在组件中访问响应。

`//component

 handleSubmit=()=>{
//dispatch an action after performing neccassary validation
const {data}=this.state; //assuming the payload data to be in your state;
this.props.callAPI(data)
 }
 Action.js

 export function callAPI(data){
  return (dispatch)=>{
    dispatch(getData(data))
  }
 }

 function getData(data){
    //use fetch/axios to call the api 
   and dispatch another action to set the response in the reducer
 }



 //in your component, use connect({mapStateToProps},{mapDispatchToProps}) 
 (nameofYourComponent) and you can use your data as props.`

答案 3 :(得分:0)

如果您不想设置Redux, 您可以单击按钮调用一个函数,调用API并为响应执行setState

`handleSubmit=()=>{
    const {data}=this.state;
    fetch(url,{add method,headers,body}).then(res=>res.json()).then(jsonData=> 
    {this.setState(jsonData)})
 }`

`render(){return(<button onChange={this.handleSubmit}/>)}`
相关问题