【问题标题】:Redux dispatching only half of the functionsRedux 只调度了一半的函数
【发布时间】:2020-08-18 01:47:43
【问题描述】:

所以,我想直接将最初为 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 = { 优先级:'优先级', };

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

【问题讨论】:

    标签: javascript redux react-redux reducers


    【解决方案1】:

    您需要将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();以避免混淆

    【讨论】:

    • 你能告诉我如何让它们工作吗?``` {priority === 0 ?

      0

      : null} {优先级 === 1 ?

      1

      : null}```
    • 更新了我的答案。请阅读 react-hooks useState 文档以更好地理解。
    • 但是当我转到不同的页面并返回时,这 1 个东西不再可见。状态正在重置吗?
    • 在这种情况下,您不能在本地维护优先级状态,而是从 redux 存储接收它并使用该值进行渲染
    • 哦,是的。非常感谢您的帮助。你几乎解决了所有问题。
    猜你喜欢
    • 2018-07-10
    • 2021-01-09
    • 2017-08-09
    • 1970-01-01
    • 2015-06-07
    • 2011-12-14
    • 1970-01-01
    • 2020-03-25
    • 1970-01-01
    相关资源
    最近更新 更多