我有一个要考虑一些条件的组件。完成如下
const Test = () => {
return <div className="text_align_center white_color">
<span><i className="fa fa-exclamation-triangle" aria-hidden="true"></i>
No internet connection. Please check your connection settings and try again
</span>
</div>
}
function checkInternetConnection(){
isOnline().then(online => {
if(online === true){
console.log("Came in here")
return <Test/>
}
});
}
然后我按如下方式调用我的函数
const App = () => (
<div className="ui container">
{checkInternetConnection()}
);
但问题是,尽管我在
checkInternetConnection
函数中获取了控制台日志,但未出现返回的组件。这可能是什么原因? 最佳答案
您的<Test/>
是由then
回调函数返回的,而不是checkInternetConnection
函数。因为您有条件地基于某些异步操作进行渲染,所以您需要采用其他方法才能正确更新组件。
一种想法是通过将无状态组件变成一个类,并在您的诺言解决时调用setState,将其变为有状态组件:
import React from 'react';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
isOnline: false // set initial state to false
};
}
componentDidMount() {
isOnline().then(online => {
this.setState({
isOnline: true; // call setState to update state and rerender App
});
});
}
render() { // use inline expression to conditionally show <Test/> if isOnline is true
return (
<div className="ui container">
{ this.state.isOnline && <Test /> }
</div>
);
}
}