react-router - 加载服务器数据的位置

标签 react-router redux

我正在使用 react-router 并导航到在 URL 中获取 ID 的组件,并且必须使用此 ID 在操作的帮助下从服务器获取数据。

目前我正在 componentWillMount Hook 中调用 Action 创建者。

到目前为止,这有效,但带来了一个问题。 在渲染方法中,我必须检查 myData 是否真的存在及其所有属性,然后才能真正渲染。

@connect(state => {myData: state.etc.myData})
export default class extends React.Component {

  componentWillMount = () => {
    this.props.dispatch(
      ActionCreators.getData(this.props.params.id)
    )
  }

  render() {
    if (this.props.myData.hasNotLoaded) return <br/>
    ...
  }

}

是否有另一种方法可以在渲染前将数据放入存储中而无需手动检查?

最佳答案

您可以订阅路由器的 onEnter 钩子(Hook)并从哪里分派(dispatch)操作。

const store = configureStore()
const routing = (<Router>
    <IndexRoute onEnter={()=>store.dispatch(myLoadDataActionCreator())}/>
</Router>)

这样你就可以避免上一个答案中的 setState 并且不要将组件与 redux 绑定(bind)。

关于react-router - 加载服务器数据的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31789639/

相关文章:

react-router - 从 React Router v2 迁移到 v4

reactjs - 为什么我的 reducer 返回 undefined,React TypeScript

reactjs - React 组件中的 JSX 将西里尔文文本显示为 habra-codabra

reactjs - 如何在非虚假应用程序中编写异步 redux 操作

reactjs - 在 "store"的上下文或 props 中找不到 "Connect(App)"。我已经有一个 <Provider> 包装组件

javascript - create-react-app with node express 获取 %PUBLIC_URL%

javascript - 将数据传递给另一个组件 OnClick

reactjs - onEnter 属性会在所有组件上触发

javascript - 嵌套 react 路由器组件在页面重新加载时不会加载/渲染?

reactjs - Redux工具包: Unable to get access to the error message sent from the server