【问题标题】:Set state of parent with react Router from Route component使用 Route 组件中的 react Router 设置父级的状态
【发布时间】:2018-09-12 07:55:52
【问题描述】:

我有一个页面,顶部有一个步骤进度条(类似于this)。在页面的中心有一些取决于当前步骤的内容。 为了管理步骤,我有一个带有步骤栏的固定组件和一个带有一些路线的开关(/step1 /step2)。 当我想从第 1 步转到第 2 步时,我必须打电话给history.push(),这样我可以轻松更改路线。

我的问题是我无法从第 2 步更新步骤栏,因为即使我将一个函数传递给父级,react 也会返回一个错误:

已超过最大更新深度。当组件在 componentWillUpdate 或 componentDidUpdate 中重复调用 setState 时,可能会发生这种情况。 React 限制了嵌套更新的数量以防止无限循环。

我的代码结构如下:

组件:父级

changeParentState(){
    this.setState({
       stateToChange: "something-changed"
    });
}
render(){
    return(
        <div> here the stepBar to update </div>
        <Switch>
             <Route path = '/step1' render = {() => <Step1Component attributes = {this.someAttributes}}/>
             <Route path = '/step2' render = {() => <Step2Component attributes = {this.changeParentState.bind(this)}}/>
        </Switch>
    );
}

组件步骤 1

render(){
  return(
     <button onClick = {() => {history.push({pathname: '/step2'})}}>next</button>
  )
}

组件步骤 2

constructor(props){
     super(props);
     this.props.changeParentState();  //error in parent when updating state
}

这里我把问题简单化了,希望不要省略一些产生我问题的代码

【问题讨论】:

  • 有点混乱,你真的需要切换路线吗?它在不同的容器上吗?或者你可以只渲染所需的组件而不使用路由吗?
  • 尝试在组件 2 上记录 this.props,检查 changeParentState 是否在组件内
  • this.props.changeParentState(); 移动到componentDidMount 内。这可能无法解决您的问题,但无论如何它都是代码中的问题。一般来说,不要通过构造函数执行任何突变。
  • Parent的渲染->Step2的构造函数->Parent的changeParentState->Parent的渲染......

标签: javascript reactjs react-router


【解决方案1】:

你不能从构造函数调用函数 试试

componentWillMount(){
  this.props.changeParentState();
}

我以前从未使用过属性,但我更喜欢

<Step2Component changeParentState = {this.changeParentState.bind(this)}}/>

【讨论】:

  • componentDidMount 更可取,因为 React 可能不会决定挂载该组件。
猜你喜欢
  • 2018-01-02
  • 2020-05-16
  • 1970-01-01
  • 2021-01-25
  • 2019-09-07
  • 2020-12-14
  • 2020-01-09
  • 2017-08-16
  • 2020-10-06
相关资源
最近更新 更多