如何正确更改 useState(array、obj 和其他)?
How correct change useState ( array, obj and other)?
我正在学习 React 并试图找出如何正确更改功能组件中的状态。你能告诉我这两个选项之间是否有区别吗?如果有,哪个更适合在工作中使用?谢谢!
const addNewTaskInState = (subtitle: string) => {
setTodoListStateArray((todoListStateArray) => {
const newTask = addNewTask(subtitle);
return [...todoListStateArray, newTask]
})
}
const addNewTaskInState = (subtitle: string) => {
const newTask = addNewTask(subtitle);
setTodoListStateArray([...todoListStateArray, newTask])
}
我认为第 2 个效率更高,您可以使用它。如果您想采用另一种方法,请查看此代码
const [state, setState] = useState([])
function SetMyState (obj) {
let auxiliaryArray = [...state]
auxiliaryArray.push(obj)
setState(auxiliaryArray)
}
第一个方法名称 updater function
您可以在此处阅读 Updating state based on the previous state
您的问题是该部分下方的答案:
- 你能告诉我这两个选项之间是否有区别吗?
In most cases, there is no difference between these two approaches
- 工作中用哪个比较好?
If you prefer consistency over slightly more verbose syntax, it’s reasonable to always write an updater if the state you’re setting is calculated from the previous state. If it’s calculated from the previous state of some other state variable, you might want to combine them into one object and use a reducer.
我正在学习 React 并试图找出如何正确更改功能组件中的状态。你能告诉我这两个选项之间是否有区别吗?如果有,哪个更适合在工作中使用?谢谢!
const addNewTaskInState = (subtitle: string) => {
setTodoListStateArray((todoListStateArray) => {
const newTask = addNewTask(subtitle);
return [...todoListStateArray, newTask]
})
}
const addNewTaskInState = (subtitle: string) => {
const newTask = addNewTask(subtitle);
setTodoListStateArray([...todoListStateArray, newTask])
}
我认为第 2 个效率更高,您可以使用它。如果您想采用另一种方法,请查看此代码
const [state, setState] = useState([])
function SetMyState (obj) {
let auxiliaryArray = [...state]
auxiliaryArray.push(obj)
setState(auxiliaryArray)
}
第一个方法名称 updater function
您可以在此处阅读 Updating state based on the previous state
您的问题是该部分下方的答案:
- 你能告诉我这两个选项之间是否有区别吗?
In most cases, there is no difference between these two approaches
- 工作中用哪个比较好?
If you prefer consistency over slightly more verbose syntax, it’s reasonable to always write an updater if the state you’re setting is calculated from the previous state. If it’s calculated from the previous state of some other state variable, you might want to combine them into one object and use a reducer.