【问题标题】:Share state between siblings in ReactJS(state not in parent)在 ReactJS 中的兄弟姐妹之间共享状态(状态不在父级中)
【发布时间】:2019-12-20 22:47:59
【问题描述】:

我有 3 个组件:Parent、Child1 和 Child2。所有状态都在 Child 2 中处理,不能移动到 Parent(目前要做很多工作)。我需要通过 Child1 的 onClick 更改状态。

这是关于即将重建的大型应用程序的一个组件,但目前没有时间。

Child2 的状态:

state = {
        selected: 0,
        type: '',
        showRootLayer: true,
        filters: {
            amount: { default: true, defaultText: 'Tutti', defaultValue: { start: 0, end: 100 }, text: '', value: '' },
            date: {
                default: true,
                defaultText: 'Week',
                defaultValue: { start: moment().subtract(1, 'week'), end: moment().subtract(1, 'day') },
                text: '',
                value: ''
            },
        }
    };

通过单击 Child1 上的按钮,我需要我的日期过滤器文本字段从状态变为“日”:

state = {
        selected: 0,
        type: '',
        showRootLayer: true,
        filters: {
            amount: { default: true, defaultText: 'Tutti', defaultValue: { start: 0, end: 100 }, text: '', value: '' },
            date: {
                default: true,
                defaultText: 'Week',
                defaultValue: { start: moment().subtract(1, 'week'), end: moment().subtract(1, 'day') },
     >>>>>>>    text: 'Day',
                value: ''
            },
        }
    };

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    React 完全是关于 data flowing down the component's tree。所以横向沟通是反模式的,很难实现。如果你不能lift your state up 考虑使用redux 来集中你的状态。有Context API,但我猜这对您没有帮助,因为它还涉及将状态移动到Provider

    【讨论】:

    • 这绝对是一种反模式。但是这个组件在少数情况下通过应用程序使用。它是以完全错误的方式构建的。不幸的是,我需要一个快速的解决方案。总的来说,所有这些组件都需要完全重建并迁移到 redux。稍后..
    • 是的。您不会在兄弟姐妹之间共享状态
    猜你喜欢
    • 2020-06-06
    • 2018-01-10
    • 2017-04-23
    • 1970-01-01
    • 2021-11-19
    • 2017-10-24
    • 1970-01-01
    • 2020-01-08
    • 1970-01-01
    相关资源
    最近更新 更多