[英]Get value from response and transfer to another component in React
I have this handleSubmit that returns me a key (verifyCode) that I should use in another component.我有这个 handleSubmit,它返回一个我应该在另一个组件中使用的密钥(verifyCode)。 How can I pass this verifyCode to another component?如何将此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;
The other component is not a child component, it is loaded after this submit step.另一个组件不是子组件,它是在此提交步骤之后加载的。 But I don't know how to transfer the const verifyCode
.但我不知道如何传输const verifyCode
。
This is the view where the components are loaded, it's a step view, one is loaded after the other, I need to get the const verifyCode in FormConfirmation这是加载组件的视图,它是一个步骤视图,一个接一个加载,我需要在FormConfirmation中获取const verifyCode
<SendForm onSubmit={handleStepSubmit} onFieldSubmit={handleFieldSubmit} />
<FormConfirmation onSubmit={handleStepSubmit} onFieldSubmit={handleFieldSubmit} />
Does anyone know how I can do this?有谁知道我怎么能做到这一点?
You need to move up the state to a component that has both as children and then pass down a function that updates as a prop您需要将状态向上移动到具有两个子项的组件,然后传递一个更新为 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>;
Check out the docs here在此处查看文档
For more complex component structures or where your passing down many levels you may want to look into reactContext对于更复杂的组件结构或向下传递多个级别的地方,您可能需要查看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>;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.