簡體   English   中英

為什么 state 更新但我無法通過 React 中的掛鈎訪問它?

[英]Why does the state update but I can't access it via hooks in React?

我在通過鈎子做出反應時無法訪問我更新的全局 state。 我創建了自定義鈎子來擺脫減速器和任何 redux 因為我不喜歡它。 一切正常,但我無法訪問我的 state。

下面是全局state的設置方法

import React, {useState, useMemo, useContext} from 'react'

function makeStore() {
  // Make a context for the store
  const Context = React.createContext();

  // Make a provider that takes an initialValue
  const Provider = ({ initialValue, children }) => {
    // Make a new state instance (could even use immer here!)
    const [state, setState] = useState(initialValue);
    // Memoize the context value to update when the state does
    const contextValue = useMemo(() => [state, setState], [state]);

    // Provide the store to children
    return <Context.Provider value={contextValue}>{children}</Context.Provider>;
  };

  // A hook to help consume the store
  const useStore = () => useContext(Context);

  return { Provider, useStore };
}

const {Provider, useStore} = makeStore();

export {
  Provider,
  useStore
}

我確保將商店提供程序包裝在 App 組件周圍

ReactDOM.render(
  <Router basename="">
    <Provider initialValue={initialState} >
      <App />
    </Provider>
  </Router>,
  document.getElementById("root")
);

App 組件很干凈,主要用於路由

const App = () => 
    <div className="App">
      <Route exact path="/" component={props => <Landing {...props} />} />
      <Route exact path="/login" component={props => <Login {...props} />} />
      <Route exact path="/register/:id" component={props => <Register {...props} />}/>
      <PrivateRoute path='/:id' Component={<Content />} />
    </div>



export default App

當我點擊登錄頁面時,輸入登錄信息,然后單擊提交,state 更新。 唯一的問題是我無法訪問組件內更新的 state。

這是登錄組件

const Login = ({...props}) => {
    const { register, handleSubmit } = useForm()
    const {auth, setAuth} = useAuth()
    const {loginUser} = AuthApi()
    const onSubmit = data => (async () => {
        const response = await loginUser(data)
        setAuth(response, true)
    })()
    useEffect(() => {
        if(auth.isAuthenticated === true)
            props.history.push('/dashboard')
    }, [])
    return(
        <div className="Auth" style={{backgroundImage: 'url(' + background + ')'}}>
            <div className="Login">
                <div className="Auth-Form Login-Form">
                    <div className="Form-Header">
                        <h4>
                            <b>Login</b>
                        </h4>
                    </div>
                    <div className="Form">
                        <form onSubmit={handleSubmit(onSubmit)}>
                            <input 
                                placeholder="Email"
                                name="email"
                                ref={register({
                                    required: "email required"
                                })}
                            />
                            <br/>
                            <input 
                                placeholder="Password"
                                name="password"
                                ref={
                                    register({
                                        required: "password required"
                                    })
                                }
                            />
                            <br />
                            <input id="submit" type="submit" placeholder="Create Profile"/>
                        </form>
                        <p className="">
                            Don't have an account? <Link to="/register/user">Register</Link>
                        </p>
                        <Link to="/" className="">Back to home</Link>
                    </div>
                </div>
            </div>
        </div>
    )
}

export default Login;

這是 useAuth 鈎子代碼

const useAuth = () => {
    const [{...auth}, setState] = useStore()

    const setAuth = (data, authenticationStatus) => {
        setState(state => {
            state.auth.token = data.token
            state.auth.user = data.user
            state.auth.loading = true
            state.auth.isAuthenticated = authenticationStatus
        })
    }

    return {auth, setAuth}
}

當登錄組件中 auth.isAutheticated 的值轉換為 true 時,什么也不會發生。 在提供程序中,state 已更新,即使在 useAuth 掛鈎中,我的控制台也會記錄當前的 state 及其更新。 然而,盡管使用了 useEffects,但我無法在登錄組件中訪問它? 有什么我想念的嗎?

此代碼僅像 componentdidmount 一樣發生 - 一次:

useEffect(() => {
        if(auth.isAuthenticated === true)
            props.history.push('/dashboard')
    }, [])

改成

 useEffect(() => {
            if(auth.isAuthenticated === true)
                props.history.push('/dashboard')
        })

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM