【问题标题】:Accessing parent state in child in React在 React 中访问子级的父级状态
【发布时间】:2017-06-09 02:19:09
【问题描述】:

我在 React 中有(例如)两个组件。第一个 app.js 是根组件。它导入一些JSON 数据并将其放入其state。这很好用(我可以在 React 开发工具中看到它)。

import data from '../data/docs.json';

class App extends Component {
  constructor() {
    super();
    this.state = {
      docs: {}
    };
  }
  componentWillMount() {
    this.setState({
      docs: data
    });
  }
  render() {
    return (
      <Router history={hashHistory}>
        <Route path="/" component={Wrapper}>
          <IndexRoute component={Home} />
          <Route path="/home" component={Home} />
          <Route path="/docs" component={Docs} />
        </Route>
      </Router>
    );
  }
}

第二个docs.js 用于显示此JSON 数据。为此,它需要访问stateapp.js。目前它出错了,我知道为什么(this 不包括app.js)。但是我怎样才能将stateapp.js 传递给docs.js

class Docs extends React.Component {
    render() {
        return(
            <div>
                {this.state.docs.map(function(study, key) { 
                    return <p>Random text here</p>; 
                })}
            </div>
        )
    }
}

【问题讨论】:

标签: javascript json reactjs state


【解决方案1】:

这样做的正确方法是将状态作为props 传递给Docs 组件。

但是,因为您使用的是React Router,所以可以通过不同的方式访问它:this.props.route.param 而不是默认的this.props.param

所以你的代码或多或少应该是这样的:

<Route path="/docs" component={Docs} docs={this.state.docs} />

{this.props.route.docs.map(function(study, key) { 
    return <p>Random text here</p>; 
})}

【讨论】:

  • 我无法发送我所有的 20 个组件的状态,有没有办法用 redux 做到这一点?
  • 这解释了什么。通过它是容易的部分,但那又如何呢?用父级的状态扩展子级的正确方法是什么,以便它们共享完全相同的对象而不是子级的状态副本?
  • @vsync 如果您将父母的状态作为道具传递给孩子,它将是同一个对象。
  • 一开始会。但是随后setState 将在孩子的某处被调用,然后孩子的状态将不同步,因为新一代开发人员非常喜欢这个新事物,称为不变性。可怕的事情。只会造成麻烦。
  • @vsync 如果你想与父母分享孩子的状态,你应该使用回调修改父母的状态并使用道具传递它
【解决方案2】:

另一种方法是:

<Route path="/docs" component={() => <Docs docs={this.state.docs}/>}>

如果您需要传递孩子:

<Route path="/" component={(props) => <Docs docs={this.state.docs}>{props.children}</Docs>}>

如果您这样做,那么您可以通过子组件中的this.props.docs 直接访问您的道具值:

{
    this.props.docs.map((study, key)=> { 
       return <p key={key}>Random text here</p>; 
    })
}

【讨论】:

    【解决方案3】:

    另一种方法是

            <Route path='/' render={ routeProps => <Home 
                {...routeProps} 
                docs={this.state.docs}
                /> 
              } 
            />
    

    在子组件中,您可以使用 docs 访问

    this.props.docs
    

    希望对你有帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-05
      • 2020-10-05
      • 2020-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-09
      相关资源
      最近更新 更多