简体   繁体   English

更新 state 数组时,React 数组 map 不更新

[英]React array map not updating when state array is updated

I have an object dashboard stored in state. Dashboard has a groups attribute that's an array of objects.我有一个存储在 state 中的 object dashboard 。仪表板有一个groups属性,它是一个对象数组。

To update the groups, I added a callback为了更新组,我添加了一个回调

// This is all in DashboardContext (useDashboard)
const [dashboard, setDashboard] = useState(props.dashboard);

const addDashGroup = (group) => {
    const newData = {
        ...dashboard,
        groups: [
            ...dashboard.groups,
            group,
        ]
    }
    setDashboard(newData);
}

Then, I map it to use.然后,我map就可以用了。

// This is used in a component that can see the `dashboard` variable with `useDashboard`
{dashboard !== undefined && dashboard.groups.length > 0 &&
    dashboard.groups.map((g, i) => <DashGroup key={g.id} index={i} group={g}/> )
}

However, when dashboard gets updated with the new groups, it doesn't update the component that uses dashboard.groups to map.但是,当dashboard使用新组更新时,它不会将使用dashboard.groups的组件更新为 map。

How can I get that component to update when dashboard.groups gets updated?如何在dashboard.groups更新时更新该组件?

Edit 1编辑 1

How I call the update callback:我如何调用更新回调:

// Part of the dashboard context.  Initial dashboard passed in as prop, then updated as needed.
const { dashboard, addDashGroup } = useDashboard();

// RTK-Query mutation
const [createDashGroup, {data: addedGroup, isLoading, error}] = useCreateDashGroupInDashboardMutation();

// Query above gets fired off when the form submits.  If it's successful, `addedGroup` gets populated (previously undefined).
useEffect(() => {
    console.log('created', addedGroup);
    if (addedGroup) addDashGroup(addedGroup);
}, [addedGroup]);

Test update the state with:测试更新 state:

const addDashGroup = (group) => {
    setDashboard((old)=> {
        return {
        ...old,
        groups: [
            ...old.groups,
            group,
        ]}
    );
}

Try it with one extra state extra一颗 state 试试

 const [dashboard, setDashboard] = useState(props.dashboard); const [extra, setExtra] = useState(0); const addDashGroup = (group) => { const newData = {...dashboard, groups: [...dashboard.groups, group, ] } setDashboard(newData); setExtra(extra+1) }

with setTimeoutsetTimeout

 const [dashboard, setDashboard] = useState(props.dashboard); const addDashGroup = (group) => { const newData = {...dashboard, groups: [...dashboard.groups, group, ] } setTimeout(() => { setDashboard(newData); }, 1000) }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM