如何在功能组件中将状态和操作传递给 Redux?

How I can pass the state and action to Redux in functional component?

我尝试使用 React Hooks 形式并通过我的 setLog() 操作将值从 Redux 存储传递到状态,据我所知我的操作不起作用但没有遇到任何类型的错误.所以,我不知道到底出了什么问题。另外,我用的是 redux-saga,但是现在,我不用它,我只是声明了它,这可能是问题吗?

SignUp.js 文件

import React from "react";
import { useForm } from "react-hook-form";
import { connect } from "react-redux";

import { setLog } from "../actions";

 function SignUp({ info }) {

 const { register, handleSubmit, setValue } = useForm();

 const onSubmit = data => setLog(data);

return (
  <React.Fragment>
    <form onSubmit={handleSubmit(onSubmit)}>
        <input {...register("login")} />
        <input {...register("password")} />
        <input type="submit" />
    </form>
    {/* <h1>{info}</h1> */}
  </React.Fragment>

);
}

const mapStateToProps = (state) => {
return {
    info: state.signUp
};
}


export default connect(mapStateToProps, { setLog })(SignUp);

操作:

 export const setLog = (data) => {
return {
    type: 'SET_LOG',
    payload: data
};
}

注册缩减器

export default(state=[],action) => {
switch(action.type){
    case 'SET_LOG':
        return [...state, ...action.payload];
    default:
        return state;
}
}

我的店铺:

import { createStore, applyMiddleware, compose } from 'redux';
import createSagaMiddleware from 'redux-saga';

import rootSaga from '../sagas';

import rootReducer from '../reducers';

const configureStore = () => {
const sagaMiddleware = createSagaMiddleware();
const store = createStore(
    rootReducer,
    window.__REDUX_DEVTOOLS_EXTENSION__
        ? compose(
              applyMiddleware(sagaMiddleware),
              window.__REDUX_DEVTOOLS_EXTENSION__(),
          )
        : applyMiddleware(sagaMiddleware),
);
sagaMiddleware.run(rootSaga);
return store;
};

 export default configureStore;

发生的事情是你没有从 props 调用 setLog,你只是调用函数而不将它与 redux 绑定,你需要使用 mapDispatchToProps 函数附加函数并在其中调用调度函数如下:

const mapDispatchToProps = (dispatch) => {
  return {
    // Calling it submitLog to avoid name collisions with the imported setLog
    submitLog: (data) => dispatch(setLog(data)),
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(SignUp);

上面的代码是将 action 连接到 redux,现在你只需要像这样调用它作为 prop:

// Now you will have the submitLog as a prop and it will be tie to redux.
function SignUp({ info, submitLog }) {

 const { register, handleSubmit, setValue } = useForm();

 const onSubmit = data => submitLog(data);

 // Rest of the code
}