【问题标题】:React native Redux useDispatch not working反应本机 Redux useDispatch 不起作用
【发布时间】:2020-04-25 15:05:52
【问题描述】:

我尝试创建一个 Redux,但当我尝试执行调度时遇到问题无法正常工作。

动作文件,userActions.js:

export const setId = () => {
   console.log("Enter to set id func");
   return {
      type: 'SET_ID'
   }
}

Reducer 文件,userReducer.js:

const INITIAL_STATE = {
    id: "",
    email: "",
    name: "",
};

const userReducer = (state = INITIAL_STATE, action) => {
    console.log('Enter to userReducer');
    switch (action.type) {
        case "SET_ID": {
            // console.log(action.payload);
        }
        default: {
            return state;
        }
    }
}

export default userReducer;

combineReducers 文件:

import userReducer from "./userReducer";
import { combineReducers } from "redux";

const allReducers = combineReducers({
    userReducer: userReducer
})

export default allReducers;

App.js 文件:

import React from 'react';
import Routes from "./Routes";
import { createStore } from "redux";
import allReducer from "./app/reducers";
import { Provider } from "react-redux";

const store = createStore(
   allReducer
);

const App = () => {
 return (
    <Provider store={store}>
      <Routes />
    </Provider>
 );
};

export default App;

在登录屏幕文件中,当我单击他调用以调度到“setId”操作时,我有按钮。
这是我的一些来自 Login.js 的代码:

import { useDispatch } from 'react-redux';
import { setId } from '../actions/userActions';
handleLoginResult = (error, user) => {
        console.log('Enter to handleLoginResult');
        if (error !== "") {
            this.setState({ generalError: error });
        } else {
            const dispatch = useDispatch();
            console.log('uid: ', user.user.uid);
            dispatch(setId());
            alert("Login!");
        }
    }

什么问题,为什么不进入 setId 操作?

【问题讨论】:

  • 根据您对this.setState() 的使用判断,这是一个基于类的组件。你不能在基于类的组件中使用 React 钩子(如 useDispatch()),你必须使用 connect() 而不是将 dispatch 函数注入到 this.props 中(使用 mapDispatchToProps 在我标记的副本中是可选的替代)

标签: reactjs react-native redux react-redux


【解决方案1】:

你可以这样试试

const userReducer = (state = INITIAL_STATE, action) =>dispatch =>{
console.log('Enter to userReducer');
switch (action.type) {
    case "SET_ID": {
        // console.log(action.payload);
    }
    default: {
        return state;
    }
}

}

【讨论】:

    【解决方案2】:

    我不太明白你的问题,但我会给你一个我的行动的例子

    export const register_user = ({ name, email, password, password_confirmation }) => {
        return dispatch => {
            dispatch(
                {
                    type: CREATE_USER
                }
            )
            let url = "/users"
            Axios.post(`${SERVER}${url}`, {
                "user": {
                    "name": name,
                    "email": email,
                    "password": password,
                    "password_confirmation": password_confirmation
                }
            })
            .then(() => {
                Alert.alert('Registrado com sucesso!')
                registerUserSuccess(dispatch)
            })
            .catch((err) => {
                registerUserError(err, dispatch)
            })
        }
    }
    
    const registerUserSuccess = (dispatch) => {
        dispatch(
            {
                type: CREATE_USER_SUCCESS
            }
        )
        this.props.navigation.navigate('Login')
    }
    
    const registerUserError = (err, dispatch) => {
        dispatch(
            {
                type: CREATE_USER_ERROR
            }
        )
        Alert.alert('Algo deu errado, verifique suas credenciais.')
    }
    

    类型是从我的 reducer 中导出的。

    并且 register_user 常量被导入并在我的注册屏幕上使用。

    【讨论】:

      【解决方案3】:

      钩子不能在函数内部使用。它们需要直接在功能组件内部声明。

      同样 useDispatch 钩子不能在类组件中使用,您必须对类组件使用 connect。

      假设您有一个类组件,根据您使用 this.setState 的方式判断,您会编写类似这样的代码

      class Login extends React.Component {
      
         ...
         handleLoginResult = (error, user) => {
              console.log('Enter to handleLoginResult');
              if (error !== "") {
                  this.setState({ generalError: error });
              } else {
                  const dispatch = this.props;
                  console.log('uid: ', user.user.uid);
                  dispatch(setId());
                  alert("Login!");
              }
          }
          ...
      
      }
      
      
      export default connect()(Login)
      

      如果你将登录写成一个函数式组件,你会这样写

      const Login = (props) => {
         const dispatch = useDispatch();
         const [state, setState] = useState({});
         ...
         const handleLoginResult = (error, user) => {
              console.log('Enter to handleLoginResult');
              if (error !== "") {
                  setState({ generalError: error });
              } else {
                  console.log('uid: ', user.user.uid);
                  dispatch(setId());
              }
          }
          ...
      }
      

      【讨论】:

        猜你喜欢
        • 2019-09-06
        • 2021-07-19
        • 1970-01-01
        • 2016-07-20
        • 2018-04-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多