【问题标题】:React Native Pass State from one component to anotherReact Native Pass State 从一个组件到另一个组件
【发布时间】:2023-03-04 18:16:01
【问题描述】:

我正在尝试使用 react native 制作登录屏幕。

这是我的 index.js

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

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

【问题讨论】:

    标签: javascript reactjs react-native


    【解决方案1】:

    您需要将状态提升到 LoginScreen 组件。 Documentation 解释得很好。使用LoginScreen 组件的state 并将此状态传递给Form 组件和onChange 中的输入Form 组件更新stateLoginScreen 组件,为此您可以将回调传递给Form零件。最后将回调传递给ButtonSubmit 组件,并在按下提交按钮时调用它。

    【讨论】:

      【解决方案2】:

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

      您可以阅读这篇文章以获得更多曝光。

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

      【讨论】:

        【解决方案3】:

        要传递状态中的数据以调用 API,您需要设置 redux 。然后你可以调用一个动作来调用 API 并在你的 reducer 中设置 API 响应。然后可以通过 props 在您的组件中访问响应。

        `//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.`
        

        【讨论】:

          【解决方案4】:

          如果你不想设置 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}/>)}`
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2019-10-23
            • 1970-01-01
            • 2021-10-15
            • 1970-01-01
            • 2022-08-17
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多