reactjs - 设置状态变量后立即调度操作

标签 reactjs redux

我有一个像这样的初始 redux 状态:

{
  loggedInUserId: null,
  comments: []
}

这是我的 React 应用程序的样子:

class App extends Component {
  componentWillMount() {
    this.props.getLoggedInUserId();
  }

  render() {
    return (
      <Switch>
        <Route exact path="/" component={HomePage} />
        <Route path="/comments" component={Comments} />
      </Switch>
    );
  }
}

在我的应用程序中,我调度一个操作 getLoggedInUserId(),该操作异步填充状态中的 loggedInUserId

主页是一个显示一些文本的愚蠢组件。我启动应用程序(路径现在为“/”),查看主页组件,然后导航到评论页面,其中包含:

componentWillMount() {
  this.props.fetchComments(this.props.loggedInUserId); // Dispatch action to do API call to fetch user's comments
}

render() {
  // Show this.props.comments nicely formatted
}

一切正常,我在评论组件中看到了评论列表。

但是如果我刷新路由 /comments 上的页面,那么当 Comments 运行 componentWillMount 时,loggedInUserId 尚未加载,因此它将调用 fetchComments(null) .

现在,为了解决这个问题,我正在评论组件中执行以下操作:

componentWillMount() {
  if (!this.props.loggedInUserId) return;
  this.props.fetchComments(this.props.loggedInUserId);
}

componentWillReceiveProps(nextProps) {
  if (!this.props.loggedInUserId && nextProps.loggedInUserId) {
    nextProps.fetchComments(nextProps.loggedInUserId);
  }
}

效果很好。但我在 10 多个组件中完成此操作,似乎需要分解大量工作,但我没有找到一种优雅的方法来完成它。

所以我想问一下,遇到这种情况,你一般是怎么处理的?欢迎任何想法:

  • HOC
  • 副作用
  • 其他图书馆

最佳答案

我正在使用Route的包装器,它检查用户是否登录,如果没有,则将他们重定向到登录页面。仅在获取经过身份验证的用户的 userId 后才会呈现包装的路由。

import * as React from 'react'
import { Route, Redirect } from 'react-router-dom'
import URLSearchParams from 'url-search-params'

class AuthRoute extends React.Component {
  componentDidMount() {
    if (!this.props.isLoading) {
      this.props.getLoggedInUserId()
    }
  }

  render() {
    if (this.props.isLoading) {
      // first request is fired to fetch authenticated user
      return null // or spinner
    } else if (this.props.isAuthenticated) {
      // user is authenticated
      return <Route {...this.props} />
    } else {
      // invalid user or authentication expired
      // redirect to login page and remember original location
      const search = new URLSearchParams({
        next: this.props.location.pathname,
      })
      const next =
        this.props.location.pathname !== '/' ? `?${search.toString()}` : ''
      return <Redirect to={`/login${next}`} />
    }
  }
}

您需要更新处理 getLoggedInUserId 操作的 reducer ,以存储 isLoading 状态。

关于reactjs - 设置状态变量后立即调度操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47952384/

相关文章:

reactjs - react 路由器连接到redux : works with links but only the URL change when dispatching push

javascript - NodeJS 和 React : bundle. js 已生成,但出现错误 404(无法加载资源)

javascript - 我如何在 Jest 中比较高阶函数

javascript - es2015中的多行赋值

javascript - 放大和缩小功能在 D3 图表中未按预期工作并使用react

reactjs - Graphql & Relay 制作案例

javascript - TextInput 的 React-Native Expo 问题

javascript - 如何在axios中获取onUploadProgress?

html - React 应用程序不透明度转换在 Chrome 中不起作用

reactjs - Redux - 如何从另一个 Action 创建者内部调用一个 Action 创建者?