反应钩子中的类似物是什么,用于正确实现isLoad?



then

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { userActions } from 'redux/actions/userActions';
class Example extends Component {
componentDidMount() {
this.props.userActions.get();
}
render() {
let { data, isLoading } = this.props.users;
if (isLoading) {
return <div>loading</div>;
}
return <div>{data}</div>;
}
}
const mapStateToProps = ({ users }) => ({
users,
});
const mapDispatchToProps = dispatch => ({
userActions: bindActionCreators(userActions, dispatch),
});
export default connect(mapStateToProps, mapDispatchToProps)(Example);

现在

import React from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { userActions } from 'redux/actions/userActions';
export default function Example() {
const users = useSelector(state => state.users);
const dispatch = useDispatch();
React.useEffect(() => {
dispatch(userActions.get());
}, [dispatch]);
if (users.isLoading) {
return <div>loading</div>;
}
return <div>{users.data}</div>;
}

使用钩子,我们第一次从化简器 isLoading = false 获得默认时间,在组件上,我们将首先执行 componentDidMount 并在渲染之前将 isLoading 设置为 true。

问题是使用反应钩子解决这种情况如何更优雅?

您的解决方案看起来不错。我有时会在我的应用程序中做这种事情。您只需要保证当您重新渲染的条件变为真时,某些内容将触发 componenet 重新渲染。在您的情况下,加载条件取决于您的 redux 状态,因此当此状态更改时,由于 useSelector 钩子,组件将自动正确重新渲染。但如果不是这种情况,您可以使用状态,如下所示:

function MyComponent() {
const [loaded, setLoaded] = React.useState(false);
if (!loaded) {
//Do something asynchronous and then use the setLoaded function to trigger the component re-render
return <View>LOADING</View>;
}
return <View>DONE</View>;
}

最新更新