useSelector挂钩首先返回未定义状态,并且在操作调用之后正确返回状态

时间:2020-04-21 21:36:24

标签: javascript reactjs redux react-redux

我是React钩子的新手,我尝试将项目与redux集成在一起,问题是在我用于登录的功能组件中,当我尝试使用useSelector获取initialState属性时,状态是不确定的。 / p>

import React, {useState} from 'react';
import loginStyles from './login.module.css';
import {useDispatch , useSelector, shallowEqual} from 'react-redux';
import {login} from '../../store/actions/actions';

export default (props) =>  {

    const initialState = {
        "email":'',
        "password":''
    }
    const dispatch = useDispatch();

    const [loginForm, setValue] = useState(initialState);


    const changeValue = (event) => {
        const name = event.target.name;
        const value = event.target.value;
        setValue(prevState => {
            return {
                ...prevState,
                [name]: value
            }
        });

    }



    useSelector((state) => {
       console.log(state)
    });


    return (
        <article className={loginStyles.main}>
            <aside className={loginStyles.left}>

            </aside>
            <aside className={loginStyles.right}>
                <div>
                    <input name="email" onChange={(event) => changeValue(event) } type = "text" value = {loginForm['email']} />
                    <input name="password" onChange={(event) => changeValue(event) } type = "text" value = {loginForm['password']} />
                    <button onClick={() => dispatch(login("jared", true))} >clicl</button>
                </div>
            </aside>
        </article>
    );

}

单击按钮后,它会打印出正确的状态,但是首先渲染时,它会打印出未定义的状态。那我该怎么修改?

这是我其余的代码。谢谢。

App.js


import React from 'react';
import {Provider} from 'react-redux';
import { createStore } from 'redux';
import reducer from './store/reducer';
import Layout from './layouts/main';
import './app.css';
function App() {

const store = createStore(reducer);

  return (
    <Provider store={store}>
      <Layout />
    </Provider>
  );
}

export default App;
import React from 'react';
import {Provider} from 'react-redux';
import { createStore } from 'redux';
import reducer from './store/reducer';
import Layout from './layouts/main';
import './app.css';
function App() {

const store = createStore(reducer);

  return (
    <Provider store={store}>
      <Layout />
    </Provider>
  );
}

export default App;
import React from 'react';
import {Provider} from 'react-redux';
import { createStore } from 'redux';
import reducer from './store/reducer';
import Layout from './layouts/main';
import './app.css';
function App() {

const store = createStore(reducer);

  return (
    <Provider store={store}>
      <Layout />
    </Provider>
  );
}

export default App;

reducer.js

const initialState = {
    logged: false,
    user: null,
    empresas: null
}

const reducer = (state = initialState, action) => {
    switch(action.type) {
        case 'ONLOGIN': {
            return {
                ...state,
                user:action.user,
                logged: true
            }
        }
        case 'ONLOGOUT': {
            return {
                ...state, 
                user: null,
                logged: false
            }
        }
    }
}

export default reducer;

actions.js


const login = (user, logged)=> {
    return {
        type:'ONLOGIN',
        user: user,
        logged: true
    }

}


export {login}

2 个答案:

答案 0 :(得分:1)

您需要在首次加载时获取存储状态以获取初始状态。

actions.js

const fetchState = () => {
  return {type: 'FETCH_STATE'}
}

reducer.js

const reducer = (state = initialState, action) => {
    switch(action.type) {
        case 'ONLOGIN': {
            return {
                ...state,
                user:action.user,
                logged: true
            }
        }
        case 'ONLOGOUT': {
            return {
                ...state, 
                user: null,
                logged: false
            }
        }
        case 'FETCH_STATE': {
            return {
                ...state, 
            }
        }
     default:
       return state;
    }
}

最后一个组件中,您需要使用React.useEffectcomponentDidMount来在首次加载时获取状态

import React, {useState} from 'react';
import loginStyles from './login.module.css';
import {useDispatch , useSelector, shallowEqual} from 'react-redux';
import {login} from '../../store/actions/actions';

export default (props) =>  {

    const initialState = {
        "email":'',
        "password":''
    }
    const dispatch = useDispatch();

    const [loginForm, setValue] = useState(initialState);

   React.useEffect(() => {
     dispatch(fetchState())
   },[])

    // remaining code

答案 1 :(得分:0)

上面的代码工作正常。我自己运行上述代码,并通过useSelector成功获取了initialState属性。

{记录:true,用户:“ jared”,empresas:null} 已记录:true 用户:“ jared” empresas:空。

项目中可能存在类似问题

  1. 您应该检查是否导出了正确的reducer功能。