My structure looks as follows:

Component 1

 - |- Component 2


 - - |- Component 4


 - - -  |- Component 5

Component 3

Component 3 should display some data depending on state of Component 5.

Since props are immutable, I can't simply save its state in Component 1 and forward it, right? And yes, I've read about Redux, but I don't want to use it. I hope that it's possible to solve it just with react. Am I wrong?

推荐答案

For child-parent communication you should pass a function setting the state from parent to child, like this


class Parent extends React.Component {
  constructor(props) {
    super(props)

    this.handler = this.handler.bind(this)
  }

  handler() {
    this.setState({
      someVar: 'some value'
    })
  }

  render() {
    return <Child handler = {this.handler} />
  }
}

class Child extends React.Component {
  render() {
    return <Button onClick = {this.props.handler}/ >
  }
}

This way the child can update the parent's state with the call of a function passed with props.

But you will have to rethink your components' structure, because as I understand components 5 and 3 are not related.

One possible solution is to wrap them in a higher level component which will contain the state of both component 1 and 3. This component will set the lower level state through props.

Javascript相关问答推荐

docx.js:如何在客户端使用文档修补程序

MongoDB中的引用

Angular:动画不启动

康威的生活游戏规则在我的Javascript版本中不起作用.''我做错了什么?

如何从调整大小/zoom 的SVG路径定义新的d属性?""

如何在 cypress 中使用静态嵌套循环

ChartJs未呈现

从页面到应用程序(NextJS):REST.STATUS不是一个函数

在FAQ Accodion应用程序中使用React useState时出现问题

在VS代码上一次设置多个变量格式

AJAX POST在控制器中返回空(ASP.NET MVC)

将基元传递给THEN处理程序

未捕获语法错误:Hello World中的令牌无效或意外

构建器模式与参数对象输入

在HTML中使用meta标记来指定定制元数据以用于使用JavaScript进行检索是不是一个坏主意?

检测带有委托的元素内部的点击,以及元素何时按其类名被选中

如何动态呈现适合未知屏幕大小的最大数量的表行?苗条的

将promise列表拆分到组.按组并行和顺序执行所有promise

使用JAVASCRIPT的偏移力矩函数库问题

阻止Electron 打开多个应用程序实例