我在Google上搜索并找到了一些相关的答案,但它们似乎并不完整。例如。 react.js don't render until ajax request finish
答案之一建议是否在模板中放置其他内容,我有以下Loader
组件在这样做:
var LoaderWrapper = function (props) {
return (
<div>
{props.loaded ? props.children :
<div className="margin-fixer">
<div className="sk-spinner sk-spinner-wave">
<div className="sk-rect1"></div>
<div className="sk-rect2"></div>
<div className="sk-rect3"></div>
<div className="sk-rect4"></div>
<div className="sk-rect5"></div>
</div>
</div>}
</div>
)
};
现在,如果我使用此包装器:
<LoaderWrapper loaded={variable!=null}>
<MyComponent variable={variable}/>
</LoaderWrapper>
在MyComponent
中:
render () {
const {variable} = this.props;
return (<div>{variable.abc}</div>)
}
问题在于仍然抱怨variable
为空。
还尝试了以下操作,抱怨同样的事情...
<LoaderWrapper loaded={false}>
<MyComponent variable={variable}/>
</LoaderWrapper>
答案 0 :(得分:0)
您一定做错了,下面的代码仍然有效,并且基于您的上述想法
import React, { Component } from 'react';
import { render } from 'react-dom';
var LoaderWrapper = function (props) {
return (
<div>
{props.loaded ? props.children :
<h2> Loading ... </h2>}
</div>
)
};
class MyComponent extends Component {
render() {
const { variable } = this.props;
return (<div>{variable.abc}</div>)
}
}
class MyApp extends Component {
constructor() {
this.state = { loaded: false };
this.changeLoading();
}
changeLoading() {
setTimeout(() => {
this.setState({
loaded: true
})
}, 2000)
}
render() {
return (
<LoaderWrapper loaded={this.state.loaded}>
<MyComponent variable={{ abc: 'This is news' }} />
</LoaderWrapper>
)
}
}
render(<MyApp />, document.getElementById('root'));
请在此处查看工作示例https://stackblitz.com/edit/react-q6wynn?file=index.js