根据用户输入更新反应上下文

时间:2020-03-09 15:38:06

标签: reactjs react-hooks react-context use-context

我有一个使用输入Hook收集用户名的表单。然后,我有了一个动态上下文,应该更新用户对象,这不会发生,因为当我在dev工具上查看输入状态时,输入状态仍然为空,并且有一个编译错误:

TypeError: Cannot destructure property 'user' of 'Object(...)(...)' as it is undefined.

UseInput:

export function useInput(initialValue){
  const [value, setValue] = useState("");
  const onChange= e =>setValue(e.target.value)
  const clear=()=>setValue("");
  const reset=()=>setValue(initialValue)
  return{
    value,
    setValue,
    onChange,
    clear,
    reset
  }
}

LoginForm:

 export default function LoginForm(){
    const {name,surname}=useInput("");
    const {user, setUser}= useContext(UserManager);
    const onSubmit =(name, surname)=>{
          setUser({name,surname})
    }

   return(
<div>
    <form>
        <input name="name" value={name} ></input>
        <input name="surname" value={surname}></input>
        <button onClick ={onSubmit}> submit</button>
    </form>
</div>
   )
}

上下文:

const UserContext= React.createContext({})
function UserManager({ children }) {
    const [user,setUser ]= useState({});
    return (
      <UserContext.Provider
        value={{user, setUser}}
      >
        {children}
      </UserContext.Provider>
    );
  }

app.js

return (
<UserManager>
<div className="App">
  <LoginForm user={user}/>
</UserManager>

); }

0 个答案:

没有答案