从响应中获取value并转移到 React 中的另一个组件

IT技术 javascript reactjs api react-hooks
2021-05-06 09:22:10

我有这个 handleSubmit,它返回一个我应该在另一个组件中使用的密钥(verifyCode)。如何将此verifyCode传递给另一个组件?

const SendForm = ({ someValues }) => {

      const handleSubmitAccount = () => {
        dispatch(createAccount(id, username))
        
          .then((response) => {
            // I get this value from data.response, its works
            const { verifyCode } = response;
          })
          .catch(() => {
          });
      };

      return(
         //the form with handleSubmitAccount()
       )
}

export default SendForm;

另一个组件不是子组件,它是在此提交步骤之后加载的。但是不知道怎么转const verifyCode

这是加载组件的视图,它是一个步骤视图,一个接一个加载,我需要在FormConfirmation中获取const verifyCode

<SendForm onSubmit={handleStepSubmit} onFieldSubmit={handleFieldSubmit} />
<FormConfirmation onSubmit={handleStepSubmit} onFieldSubmit={handleFieldSubmit} />

有谁知道我怎么能做到这一点?

1个回答

您需要将状态向上移动到具有两个子项的组件,然后传递一个更新为 prop 的函数

import React from "react";

export default function App() {
    const [value, setValue] = React.useState(0);
        return (
            <div className="App">
                <Updater onClick={() => setValue(value + 1)} />
                <ValueDisplay number={value} />
           </div>
       );
}

 const Updater = (props) => <div onClick={props.onClick}>Update State</div>;
 const ValueDisplay = (props) => <div>{props.number}</div>;

此处查看文档

对于更复杂的组件结构或向下传递多个级别的地方,您可能需要查看reactContext

import React from "react";

//Set Default Context
const valueContext = React.createContext({ value: 0, setValue: undefined });

export default function App() {
    const [value, setValue] = React.useState(0);
        return (
           <div className="App">
              {/** Pass in state and setter as value */}
              <valueContext.Provider value={{ value: value, setValue }}>
                  <Updater />
                  <ValueDisplay />
              </valueContext.Provider>
         </div>
    );
}

const Updater = () => {
     /** Access context with hook */
     const context = React.useContext(valueContext);
     return (
         <div onClick={() => context.setValue(context.value + 1)}>Update State</div>
     );
};
 const ValueDisplay = () => {
     /** Access context with hook */
     const context = React.useContext(valueContext);
      return <div>{context?.value}</div>;
 };