在不使用setState的情况下对状态使用筛选器



我知道react建议使用setCommand来更新我的状态,但如果不直接对状态使用filter,我找不到最快的方法来更新命令。有人能告诉我如何使用setCommand吗?

更正我只是忘记了过滤器中的返回:

function useCommand() {
const [command, setCommand] = useState([]);
const handleCommand = (barcode) => {
let newCommand = command.filter(item => { return (item.code == barcode) ? item.quantity++ : item})
setCommand(newCommand)
}
return [command, handleCommand];
}

filter函数返回一个新数组,不修改现有数组。因此,您可以直接在状态上使用filter,因为它不会修改状态。在您的案例中,您已经使用command.filter(article => {(article.code == barcode) ? article.quantity++ : article})创建了一个新数组,但您没有将该新数组存储在变量中。一旦将其存储在变量中,就可以简单地使用该变量来使用setCommand设置状态。

这是代码:

function useCommand() {
const [command, setCommand] = useState([]);
const handleCommand = (barcode) => {
var newCommand = command.filter(article => {(article.code == barcode) ? article.quantity++ : article});
setCommand(newCommand);
}
return [command, handleCommand];
}

最新更新