从 redux-saga 访问 props.location 对象

Access props.location object from redux-saga

我的最终目标是在进行 API 调用时访问 redux-saga 中的 this.props.location.pathname。这是我目前的工作解决方案,尽管反应会引发错误。我正在使用 mxstbr/react-boilerplate-brand 作为我的代码库。

在我的包装组件 App 中,我的渲染方法中有以下行。

render() {
  this.props.onUpdateLocation(this.props.location)
}

在我的 mapDispatchToProps 中,我有以下内容。基本上我只是将 this.props.location 保存到 React 存储中:

function mapDispatchToProps(dispatch) {
  return {
    onUpdateLocation: (location) => {
      dispatch(updateLocation(location));
    },
    dispatch,
  };
}

在我的 redux-saga 中,我从状态访问该位置,并根据需要使用它;但是,这是 React 引发的错误。

warning.js:44 Warning: setState(...): Cannot update during an existing state transition (such as within `render` or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to `componentWillMount`.

我不能把它放在 componentWillMount 中,因为它只会在应用程序启动时触发一次,而且我不能把它放在 componentWillUpdate 中,因为 this.props.locationrender 方法。我不能把它放在 componentDidUpdate 中,因为那太晚了。

我是否只是缺少一些简单明显的方法来访问我的 redux-saga 中的 react-router 位置?

如果你有 <Route path='profile' component={ Profile } /> 配置文件组件可以在第二个参数 ownProps 中访问 react-router 道具:

mapStateToProps(state, [ownProps])mapDispatchToProps(dispatch, [ownProps])

长话短说:

export class App extends React.Component {
  componentWillMount() {
    this.props.onUpdateLocation(this.props.location.pathname);
  }
  componentWillReceiveProps(nextProps) {
    this.props.onUpdateLocation(nextProps.location.pathname);
  }
  render() {
    // Render stuff here
  }
}

function mapDispatchToProps(dispatch) {
  return {
    onUpdateLocation: (location) => {
      dispatch(updateLocation(location));
    },
    dispatch,
  };
}

我的 reducer 接收动作并更新状态 location。现在我可以使用从状态中获取 location 的选择器访问当前路径名。

长答案:

IGL 的回答是非常好的信息,尤其是通配符命名信息,您可以在路由中使用它并由 mapDispatchToPropsownProps 参数返回。这是我解决问题的方法...

最初我以为警告是关于正在访问 this.props.location 或其他东西;然而,这是一个简单得多的问题。 React 不喜欢你调用一个函数而不是因为像点击这样的动作。提示解决方案的警告消息使我走上了正确的轨道。

首先要了解在何时何地触发了什么,我将每个 React 生命周期函数放在我的代码中,并在它们被命中时进行控制台记录。 componentWillMount, componentDidMount, componentWillReceiveProps, shouldComponentUpdate, componentWillUpdate, componentDidUpdate, componentWillUnmount.

我发现 componentWillMount 在初始页面加载时触发,并且 componentWillReceiveProps 在每次导航时触发。考虑到这一点,我控制台登录 this.props.location 并发现 componentWillReceiveProps 仍然有旧位置;但是,它需要一个参数 nextProps 来表示新位置。所以,nextProps.location 就是我想要的。我把它放在我的 App 容器中,它把其他容器作为它的子容器,现在我可以访问我的 sagas 中的当前位置,我用它来进行 API 调用。