Reactjs React native Redux useDispatch不工作

Reactjs React native Redux useDispatch不工作,reactjs,react-native,redux,react-redux,Reactjs,React Native,Redux,React Redux,我试图创建一个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: "", na

我试图创建一个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;
组合减速器文件:

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操作?

我不太理解您的问题,但我会给您举一个我的操作示例

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.')
}
该类型是从我的减速器导出的


并且register\u user常量被导入并在我的register屏幕上使用。

您可以这样尝试

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;
    }
}

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

此外,不能在类组件内部使用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());
        }
    }
    ...
}

这回答了你的问题吗?从您使用的
this.setState()
判断,这是一个基于类的组件。不能在基于类的组件中使用React钩子(如
useDispatch()
),必须使用
connect()
dispatch
函数注入
this.props
(使用mapDispatchToProps作为标记的重复项是可选的)
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());
        }
    }
    ...
}