Redux 只调度了一半的函数

Redux dispatching only half of the functions

所以,我想直接将最初为1的优先级值替换为不同的值。我为它创建了一个 redux 函数,但它不止一次发送该函数。

动作

export const editPriority = (id, listID, newPriority) => {
  return {
    type: TRELLO_CONSTANTS.PRIORITY,
    payload: { id, listID, newPriority },
  };
};
      const { id, newPriority } = action.payload;
      const card = state[id];
      card.priority = newPriority;
      return { ...state, [`card-${id}`]: card };
    }

导出常量TRELLO_CONSTANTS = { 优先级:'PRIORITY', };

and here's my function -

import {editPriority} from './actionTypes.js';

const card=({dispatch})=> {
  const [newPriority, priority] = useState(); 
}

const changePriority = (e) => {
    // newPriority(e);
    priority(e);
    dispatch(editPriority(id, listID, priority));
    console.log(priority);
  };

// and the main function


<button onClick={() => changePriority(1)}>1</button>
<button onClick={() => changePriority(2)}>0</button>

{priority === 0 ? <p>0</p> : null}
{priority === 1 ? <p>1</p> : null}

所以每当我点击按钮时,它只会调度 id 和 listID,而不是优先级。另外,我也无法使最后 2 个三元运算符起作用。这是访问它们的错误方式吗?

这是我在 redux 扩展中得到的输出 -

{
  type: 'PRIORITY',
  payload: {
    id: 'card-0',
    listID: 'list-0'
  }
}

您需要将 e 直接传递给 editPriority,因为 state 更新本质上是异步的,priority(e) 引起的更改不会立即反映出来.

const changePriority = (e) => {
    // newPriority(e);
    priority(e);
    dispatch(editPriority(id, listID, e));
 };

建议:

在reducer中,不要直接改变原始状态

const { id, newPriority } = action.payload;
const card = {...state[id]};
card.priority = newPriority;
return { ...state, [`card-${id}`]: card };

您的优先州名称也是 newPriority

因此,在渲染中使用该值:

{newPriority === 0 ? <p>0</p> : null}
{newPriority === 1 ? <p>1</p> : null}

建议:在命名状态时可以使用const [priority, setPriority] = useState();以避免混淆