【问题标题】:redux-simple-router - perform action based on URLredux-simple-router - 基于 URL 执行操作
【发布时间】:2016-01-07 22:09:50
【问题描述】:

我正在使用带有 redux-simple-router 的 Redux。

这就是我想要做的。用户点击如下 URL: http://localhost:3000/#/profile/kSzHKGX 其中kSzHKGX 是配置文件的 ID。这应该路由到配置文件容器,其中填写了 ID 为 kSzHKGX 的配置文件的详细信息。

我的路线如下所示:

export default (
  <Route path="/" component={App}>
    ...
    <Route path="profile" component={Profile} />
    ...
  </Route>
)

所以点击上面的链接会给我Warning: [react-router] Location "undefined" did not match any routes

我的容器如下所示:

@connect(
  state => state.profile,
  dispatch => bindActionCreators(actionCreators, dispatch)
)
export class Profile extends Component {
  constructor(props) {
    super(props)
  }
  componentDidMount() {
    const { getProfileIfNeeded, dispatch } = this.props
    getProfileIfNeeded()
  }
  render() {
    return (
      <section>
      ...
      </section>
    )
  }
}

所以通常我的容器只会像 Redux 中一样从状态中填充。

基本上我需要有一种方法在路由中做一些通配符。比我需要将 URL 传递给从 API 中提取正确配置文件的操作。问题是,react-simple-router 是否可行?我可以使用 UPDATE_PATH 以某种方式做到这一点吗?这会是正确的 Redux 方式吗?还是我应该使用其他东西?

【问题讨论】:

  • 我怀疑您的路由器配置有问题,因为您不应该收到undefined - 可能是错误的或丢失的历史记录?您可能也想分享它。但是对于您的 URL,您需要定义一个类似 profile/:id 的路径,然后您的组件将在其 props 中收到一个 params 对象,该对象具有您需要的配置文件的 id。
  • 你想从历史上看到什么? question> 现在,当我以 profile/:id 的身份执行路由时,应用程序向 API 发出请求到http://localhost:5000/profiles/undefined (???)
  • 我的意思是你如何使用history 库。例如。 basic demo 开箱即用,那么你的有什么不同呢?我们可以看看你的实现吗?如果在你的Profile 组件上记录this.props,你会看到什么?
  • 我正在使用这个样板应用程序:github.com/anorudes/redux-easy-boilerplate。历史随之而来,我没有改变任何东西。是的,我确实在道具中看到了 param.id。所以我很清楚此时该做什么。谢谢!

标签: javascript reactjs redux react-router-redux


【解决方案1】:

按照 Josh David Miller 的建议,我将路线设计成如下所示:

<Route path="admin/profile/:id" component={Profile} />

比我的容器有这个方法从 API 获取配置文件:

componentWillMount() {
  const { getProfile, dispatch } = this.props
  getProfile(this.props.params.id)
}

这要清理(如果没有它,我会在组件加载时瞬间显示之前的配置文件 - 在我点击 componentWillMount 中的 API 之前)

componentWillUnmount() {
  this.props.unmountProfile()
}

更新:

作为清理的替代方法,我正在考虑使用Container Component Pattern。基本上让外部组件进行数据获取并将数据作为道具传递给内部组件。

【讨论】:

    猜你喜欢
    • 2016-03-30
    • 2016-04-26
    • 2016-05-23
    • 2016-04-15
    • 1970-01-01
    • 2017-06-23
    • 2018-07-24
    • 1970-01-01
    • 2016-01-27
    相关资源
    最近更新 更多