这是关于我刚刚在这里提出的问题:React expose component function
因此,当在函数公开的 2 个组件上使用 componentDidMount 时,数据函数的 componentDidMount 看起来需要一些时间来加载,然后这会导致返回一个空数组。我对 react 还很陌生,所以我不确定这是否是使用它们的正确方法。
class Data extends React.Component {
constructor() {
super();
this.state = {
names: []
}
}
componentDidMount() {
$.get('data.json', function (result) {
this.setState({
names: result.names
});
}.bind(this));
}
getNames(){
return this.state.names;
}
render(){
return (<div></div>);
}
}
class Layout extends React.Component {
constructor(){
super();
this.state = {
test: []
};
}
componentDidMount() {
this.state.test = this.refs.hello.getNames();
console.log(this.refs.hello.getNames());
}
something(){
console.log(this.state.test);
}
render(){
return(
<div>
<Data ref='hello' />
{this.something()}
</div>
)
}
}
const app = document.getElementById('app');
ReactDOM.render(<Layout />, app);
最佳答案
您错误地在布局组件中为状态赋值,例如 this.state.test = this.refs.hello.getNames();
,您应该在其中使用 setState( );此外,最好在 Layout
组件中检索数据,如果你也想使用 Data
组件中的数据,那么你可以将它作为 prop 传递给相同的 like
class Data extends React.Component {
constructor() {
super();
}
render(){
console.log(this.props.names)
return (<div></div>);
}
}
class Layout extends React.Component {
constructor(){
super();
this.state = {
test: []
};
}
componentDidMount() {
$.get('data.json', function (result) {
this.setState({
test: result.names
});
}.bind(this));
}
something(){
console.log(this.state.test);
}
render(){
return(
<div>
<Data ref='hello' names={this.state.test}/>
{this.something()}
</div>
)
}
}
const app = document.getElementById('app');
ReactDOM.render(<Layout />, app);
关于javascript - React 暴露组件功能并使用 ComponentDidMount 获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41475682/