javascript - 在React中访问子级的父级状态

标签 javascript json reactjs state

我在 React 中有(例如)两个组件。第一个 app.js 是根组件。它导入一些 JSON 数据并将其置于其状态中。这工作得很好(我可以在 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 数据。为此,它需要访问 app.jsstate。目前它出错了,我知道为什么(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>
        )
    }
}

最佳答案

执行此操作的正确方法是将状态作为 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>; 
})}

关于javascript - 在React中访问子级的父级状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41825557/

相关文章:

javascript - jQuery - 阻止用户输入字符 '>' 但允许句号

javascript - 替换字符和单词

javascript - 返回最短单词和最长单词的长度差值(使用 for 循环)

javascript - 将Class移除到具有它的元素

reactjs - 如何在React中显示API错误句柄?

javascript - 如何防止 React 卸载 Semantic UI React 中上一个选项卡的内容?

json - Typescript 中 Json 中的枚举与接口(interface)?

javascript - 将数据存储为 JSON 比将其存储在 JavaScript 对象中的优势

json - Apache Pig中的Json解析

javascript - 将方法传递给子组件