我在 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.js
的 state
。目前它出错了,我知道为什么(this
不包括 app.js
)。但是我怎样才能将 state
从 app.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/