因此,我想直接将最初为1的priority值替换为不同的值。我为它创建了一个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,而不是优先级。另外,我也无法使最后两个三元运算符工作。这是一种错误的访问方式吗?
这是我在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));
};
建议:
在还原器中,不要直接改变的原始状态
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();
以避免混淆