取决于react / redux无法正常工作

时间:2017-03-11 18:00:59

标签: ajax reactjs redux fetch thunk

我是新手,并尝试使用这些功能制作我的第一个项目:react,redux,react-router,redux-thunk。我用json从url获取数据。它在强大的pc上工作正常,在柳条上它不会工作因为我的支持,它开始获取然后它尝试渲染没有数据的组件,然后它从网址获取数据...同样的结果我有刷新时innerpage,它会在获取数据之前尝试渲染组件。

所以这里是创建商店:

const middleware = [routerMiddleware(hashHistory)];

const store = createStore( combineReducers({
    reducers:reducers,
    routing:routerReducer
}),compose(applyMiddleware(...middleware, thunk), 
          window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()));

const history = syncHistoryWithStore(hashHistory, store);

然后这是我的提供者:

ReactDOM.render(
    <Provider store={store}>
    <Router history={history}>     
      <Route path="/" component={withTransition(App)}>
        <IndexRoute component={Projects} />
        <Route path="project/:id/" component={SingleProject}>
        </Route>
      </Route>
    </Router>
    </ Provider>,
    document.getElementsByClassName('root')[0]
)

我以这种方式获取数据:

function fetchProjRequest(){
  return {
    type: "FETCH_PROJ_REQUEST"
  }
}

function fetchProjSuccess(payload) {
  return {
    type: "FETCH_PROJ_SUCCESS",
    payload
  } 
}

function fetchProjError() {
  return {
    type: "FETCH_PROJ_ERROR"
  }
}

function fetchProj() {
  const URL = "http://****.com/data/proj";
  return fetch(URL, { method: 'GET'})
     .then( response => Promise.all([response, response.json()]));
}

class App extends Component{

  constructor(props){
    super(props);
    this.props.fetchProjWithRedux();

  }


  render(){
    return (
     <div className={styles.app}>
       <Logo />
        <TagFilter />
        <div className={styles.content}>
          {this.props.children}
        </div>
      </div>
    )
  }
}

function mapStateToProps(state){
  return {
    proj: state.proj
  }
}

export default connect(
  state => ({
    proj: state.reducers.projects.proj
  }),
  dispatch =>({
    fetchProjWithRedux: () => {
      fetchProj().then(([response, json]) =>{
        if(response.status === 200){
          dispatch(fetchProjSuccess(json))
        }
        else{
          dispatch(fetchProjError())
        }
      })
    },
  })
)(App);

如果有人告诉我我错了,那会很有意思:(这对我来说非常重要!

1 个答案:

答案 0 :(得分:1)

Here是一个专门用来照顾你需要的东西。

确保在缩减器中引入isDataLoaded boolean道具,并在调用true时使其FETCH_PROJ_SUCCESS。希望它有所帮助。

对您的代码进行了一些更改:

import dataLoader from './dataLoader';

const AppWithLoader = dataLoader(App);

export default connect(
  state => ({
    isDataLoaded: state.proj.isDataLoaded,
    proj: state.reducers.projects.proj
  }),
  dispatch =>({
    dispatchGetData: () => {
      fetchProj().then(([response, json]) =>{
        if(response.status === 200){
          dispatch(fetchProjSuccess(json))
        }
        else{
          dispatch(fetchProjError())
        }
      })
    },
  })
)(AppWithLoader);