最近我偶然发现了以下代码:
import { Component } from 'react';
import { connect } from 'react-redux';
import { setUser } from './store';
const doSomeSideEffect = ({ firstName, lastName }) => document.title = `Hello ${firstName} ${lastName}`;
class App extends Component {
state = {
isLoading: false
}
async componentDidMount() {
console.log(this.props.user); // some initial state like: { firstName: undefined, lastName: undefined, isAuthorized: false }
if (!this.props.user.isAuthorized) await this.loadData();
console.log(this.props.user); // { firstName: 'Foo', lastName: 'Bar', isAuthorized: true }
doSomeSideEffect(this.props.user);
}
async loadData() {
this.setState({ isLoading: true });
const data = await new Promise(resolve => setTimeout(() => resolve({ firstName: 'Foo', lastName: 'Bar', isAuthorized: true }), 5000));
this.props.setUser(data);
this.setState({ isLoading: false });
}
render() {
return this.state.isLoading ? 'Loading' : 'Loaded';
}
}
export default connect(user => ({ user }), { setUser })(App);
我知道毕竟这只是纯Javascript,但令我感到困惑的是在this.props
中的await
之后引用了componentDidMount
,实际上该代码可以按预期工作。任何人都可以说以这种方式引用道具是好是坏做法,为什么?这不是种族问题吗?