首页 > 解决方案 > 我可以在这个问题中使用像 setState 这样的调度吗?

问题描述

我正在将此应用程序转换为 Redux,但自定义句柄函数正在使用 {name , value } = event.target

  handleChange = event => {      
      const { name, value } = event.target;

      this.setState({
          [name] : value
      });
  }

在这里,他们动态地为所有字段采用单个处理程序,但在我的情况下,我使用了 dispatch 'react-redux hooks' 而不是 setState

     this.setState({
          [name] : value
      });

     dispatch(reducerName({
          type: 'SET_NAME / SET_EMAIL / SET_any_other_fiels',
          payload: value
      })

我的解决方案是为每个字段制作 handleChange[type] 或者我可以做其他事情?我有领域

let initialState = {
   name,
   email,
   walletid:'',
    payout:0,
    bank:{          
      bank: 0,
      expenditures: 0,
      fees: 0,
      income: 0,
      receipts: 0,
      rejected: 0          
    }
}
i want to share the single case in reducer to add all fields 

标签: reactjsredux

解决方案


您可以直接在动作有效负载中传递键、值并在减速器中使用它们。

 var payload = {
           name: name,
           value: value
          }

 dispatch(reducerName({
              type: 'SETFIELDS',
              payload: payload
          })

const reducer = (state = initialState, action) => {
    if (action.type == 'SETFIELDS') {
            // Return new modified state
            return {
                ...state,
                [action.payload.name]: action.payload.value
            };
        }
        // Default
        return state;
}

推荐阅读