Reactjs useReducer未正确更新我的状态
我的减速机没有像我被人看到的那样工作 目标是处理包含有关复选框数据的对象数组:Reactjs useReducer未正确更新我的状态,reactjs,typescript,react-hooks,react-component,use-reducer,Reactjs,Typescript,React Hooks,React Component,Use Reducer,我的减速机没有像我被人看到的那样工作 目标是处理包含有关复选框数据的对象数组: <Checkbox key={e.uuid} checked={state[e.uuid]?.checked} onClick={() => {handleCheckBox(e)}}>{e.name}</Checkbox> 此时,它非常完美,但当我在web控制台中取消文件对象时,我发现: checked: false choicePoint: 1 name: "A point
<Checkbox key={e.uuid} checked={state[e.uuid]?.checked} onClick={() => {handleCheckBox(e)}}>{e.name}</Checkbox>
此时,它非常完美,但当我在web控制台中取消文件对象时,我发现:
checked: false
choicePoint: 1
name: "A point."
qte: 0
uuid: "23cb1136-31e8-3b36-9ad6-f37c46276390"
支票现在是假的???但是怎么做呢
此时我的复选框未选中
这是我的减速机:
import { useReducer } from 'react'
export interface ICheckBox {
uuid: string,
checked:boolean,
qte:number,
choicePoint:number,
name:string
}
export function toggleCheckBox(uuid: string) {
return <const>{
type: 'TOGGLE_CHECKBOX',
uuid
}
}
export const initialState: Record<string,ICheckBox> = {}
type State = typeof initialState
type Action = ReturnType<
typeof toggleCheckBox
>
function reducer(state: State, action: Action): State {
switch (action.type) {
case 'TOGGLE_CHECKBOX':
{
const newState = {...state};
const checkbox = newState[action.uuid];
checkbox.checked = !checkbox.checked
console.log("checkbox",checkbox);
newState[action.uuid] = checkbox;
console.log("newstate",newState[action.uuid]);
return {...newState}
}
default:
return state
}
}
export function useCheckBoxReducer(state = initialState) {
return useReducer(reducer, state)
}
import { useReducer } from 'react'
export interface ICheckBox {
uuid: string,
checked:boolean,
qte:number,
choicePoint:number,
name:string
}
export function toggleCheckBox(uuid: string) {
return <const>{
type: 'TOGGLE_CHECKBOX',
uuid
}
}
export const initialState: Record<string,ICheckBox> = {}
type State = typeof initialState
type Action = ReturnType<
typeof toggleCheckBox
>
function reducer(state: State, action: Action): State {
switch (action.type) {
case 'TOGGLE_CHECKBOX':
{
const newState = {...state};
const checkbox = newState[action.uuid];
checkbox.checked = !checkbox.checked
console.log("checkbox",checkbox);
newState[action.uuid] = checkbox;
console.log("newstate",newState[action.uuid]);
return {...newState}
}
default:
return state
}
}
export function useCheckBoxReducer(state = initialState) {
return useReducer(reducer, state)
}
const [state,dispatch] = useCheckBoxReducer(question.choices.reduce((prev,cur) => {
prev[cur.uuid] = {
uuid: cur.uuid,
checked:false,
qte:0,
choicePoint:cur.choicePoints,
name:cur.name
}
return prev
},{} as Record<string,ICheckBox>));
<Checkbox key={e.uuid} checked={state[e.uuid]?.checked} onClick={() => {handleCheckBox(e)}}>{e.name}</Checkbox>
const handleCheckBox = (choice:IChoice) =>{
dispatch({
type: "TOGGLE_CHECKBOX",
uuid: choice.uuid
})
}