【发布时间】:2020-08-18 23:45:48
【问题描述】:
在我手动重新渲染整个页面之前,我的标题组件没有收到新的道具。我想知道为什么?
基本上我有四个条件来呈现我的标题:空闲、加载、成功、失败。
- 在空闲时,用户会看到 LoggedOutNavbar
- 在加载时,用户会看到 LoadingNavbar
- 成功后,用户会看到 LoadedNavbar
- 失败时,用户会看到 LoggedOutNavbar
用户第一次访问登录页面时,状态为idle。如果他然后点击登录按钮,则登录成功,但标头没有收到新的加载和成功状态作为道具。因此,标头保持与注销状态相同。但是,当手动重新加载页面并再次分派操作时,新的道具可用并显示新的标题。我想知道如何在不手动重新加载页面的情况下获得相同的结果?
export class Header extends Component {
componentDidMount() {
this.props.getProfile();
this.props.loadUser();
}
render() {
const {profile} = this.props.profile;
const isFetching = this.props.isFetching
const {isAuthenticated} = this.props.auth
if (isFetching === "idle") return (<LoggedOutNavbar />)
if (isFetching === "loading" ) return (<Fragment> <LoadingNavbar /> </Fragment> )
if (isFetching === "success") return (<LoadedNavbar profile = {profile[0]} isAuthenticated ={isAuthenticated}/>)
if (isFetching === "failure") return (<LoggedOutNavbar />)
}
}
function mapStateToProps(state, ownProps) {
const auth = state.auth
const profile = state.profile
const isFetching = state.profile.isFetching
return { auth, profile, isFetching}
};
export default connect(
mapStateToProps,
{ getProfile, loadUser }
)(Header);
header.js:34 idle // Logged Out state
header.js:34 loading
header.js:34 success // Logged in state, after manually rerendering
header.js:34 success // Logged in state, after manually rerendering
header.js:34 idle // Logged Out state
header.js:34 idle // Logged in state but header is still in idle
header.js:34 idle // Logged in state but header is still in idle
编辑: 在检查我的 Redux 开发工具时,我发现配置文件实际上并没有从空闲状态变为另一个状态。我认为登录后不会再次调用 getProfile 函数。
【问题讨论】:
-
你能通过在 Redux devtools 中查看 state 来确认 state 已经改变了吗?
-
@Wezelkrozum 你是对的。在 Redux-Devtool 中显示的状态没有变化。它保持空闲状态。我想这是因为
ComponentDidMount中的函数getprofile在组件加载时仅调用一次,但在登录后不会调用第二次。 -
@dan_boy 使用 effect 使 Header 成为功能组件可能更简单。如果您看到文档的类示例,那么您会看到您还需要实现
componentDidUpdate以查看是否某些道具发生了变化。您还可以在登录时设置所需的 redux 状态值,然后 mapStateToProps 应该加载更改的值(除非您在 reducer 中改变状态)。
标签: reactjs redux react-redux