在哪里加载服务器数据

时间:2015-08-03 14:15:47

标签: react-router redux

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

目前我正在componentWillMount挂钩中调用动作创建者。

到目前为止,这有效,但会带来问题。 在渲染方法中,我必须检查,如果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/>
    ...
  }

}

在没有人工检查的情况下,还有其他方法可以将数据导入商店吗?

2 个答案:

答案 0 :(得分:9)

您可以订阅路由器的onEnter挂钩和派遣行动。

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

因此,您可以避免以前的回答setState,也不要将组件与redux捆绑在一起。

答案 1 :(得分:1)

您应该创建一个回叫,例如:

componentDidMount() {
    myStore.addChangeListener(this._onChange);
},
componentWillUnmount() {
    myStore.removeChangeListener(this._onChange);
}

然后在以下反应函数中执行以下操作:

if

我假设您正在使用反应路由器的mixins,如果没有,请查看文档,它们有一些值得关注的有用功能。

我认为你不需要render()方法中的[{ "restaurant": { "_id": "55095363649e380e12cc1868", "name": "Skygarage" }, "sumSP": 241 }, { "restaurant": { "_id": "54e6afe5c1184450416e3118", "name": "Farmaaish" }, "sumSP": 3920 },{ "restaurant": { "_id": "55095363649e380e12cc1868", "name": "Skygarage" }, "sumSP": 2333 },{ "restaurant": { "_id": "55095363649e380e12cc1868", "name": "Skygarage" }, "sumSP": 2445 }] 逻辑,react会通过虚拟dom管理来处理它,并知道何时加载它和数据。