我在React中有(例如)两个组件。首先, app.js
,是根组件。它进口一些 JSON
数据并将其放入其中 state
。这很好(我可以在React devtools中看到它)。
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
数据。要做到这一点,它需要访问 state
的 app.js
。目前它出错了,我知道为什么(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>
)
}
}