1

this.props.location.pathname我的最终目标是在进行 API 调用时访问redux-saga 内部。这是我当前的工作解决方案,尽管反应引发错误。我正在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.location得到了更新。render我不能把它放进去,componentDidUpdate因为太晚了。

我只是错过了一些简单的方法来访问我的 redux-saga 中的 react-router 位置吗?

4

2 回答 2

2

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

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

于 2016-09-24T11:57:50.487 回答
0

TL;博士:

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,
  };
}

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

长答案:

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

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

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

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

于 2016-10-18T21:26:24.947 回答