在React中填充初始状态

时间:2016-11-21 04:05:09

标签: javascript reactjs redux react-redux

我是React的新手,我必须说,这很困惑。我构建了我的应用程序在我的根/容器组件中获取数据的第一次迭代。这是容器

class HomePage extends React.Component{

  constructor(props) {
    super(props);
    this.state = {user: null};  

  }
  componentWillMount() {

    getUserData(xobni_api).then((result) =>{
      this.setState({user : result});

    });


  render(){
    return(

        {this.state.user &&
        <div className="col-md-8 middle-pane">
          <Viewer images={this.state.user} />
        </div>
        }

    );
  }

}

这是getUserData函数,

export function getUserData(url){

  return fetch(url, { credentials : 'include'})
              .then((response) => { return response.json();})
              .then((data) =>{ return new User(data.public_id, data.yahoo_profile.givenName, data.yahoo_profile.familyName, data.credentials[0].account);});
}

现在我正在重组我的应用程序并希望使用Redux管理数据。这是我的condifgureStore

export default function configureStore(initialState){
  return createStore(
    rootReducer,
    initialState,
    applyMiddleware(reduxImmutableStateInvariant())
  );
}

我正在index.js

中实例化商店
const store = configureStore(initialState);

然后我需要将这个状态传递给我的个人Reducers,就像这个。

export default function homePageReducer(state, action){
  switch(action.type){
    case 'SEND_IMAGE':
      //send image

    default:
      return state;
  }
}

我似乎无法找到正确的方法来做到这一点。我真的很感激,如果有人可以提供一个稍微详细的答案,我可以如何将api调用从我的组件中移出,在商店中进行调用,设置初始状态然后将其传递回组件。 提前谢谢。

2 个答案:

答案 0 :(得分:1)

我抨击我的一个简约概念是:

  

调度操作以更新商店,无论是什么(获取数据,调用chrome API等)

让我们在你的案例中尝试这个概念:

dispatch

接下来的问题是,你如何获得import store from 'path/to/store'; store.dispatch({ type: 'ACTION_TO_BE_DISPATCHED' }); 功能。一种方法是导入实例化的商店并像这样调用调度函数:

redux-thunk

那很糟糕。现在,您必须在每次需要分派操作时导入商店。

介绍redux-thunk !!请参阅here以了解您为什么需要此功能。使用fetchAndUpdateStore() { // notice that this returns a function return (dispatch) => { fetch(url, { credentials : 'include'}) .then((response) => { return response.json();}) .then((data) => { // create a new user const newUser = new User(data.public_id, data.yahoo_profile.givenName, data.yahoo_profile.familyName, data.credentials[0].account); // now you can dispatch function easily. dispatch({ type: 'UPDATE_STORE_WITH_NEW_USER' payload: { user: newUser, }, }); }); } } ,您可以创建如下操作:

someBasicAction = () => ({
  type: 'BASIC_ACTION',
});

而不是像这样的简单基本动作:

import { connect } from 'react-redux';
import fetchAndUpdateStore from 'path/to/that/action';

const mapStateToProps = (state) => ({
  user: state.user,
});

const mapDispatchToProps = (dispatch) => ({
  fetchThenUpdate: () => (
    dispatch(fetchAndUpdateStore())
  ),
});

connect(mapStateToProps, mapDispatchToProps)(YourComponent);

现在,最后一部分是调度操作并将组件连接到商店中的数据。

this.props.fetchThenUpdate

最后在您的组件中,您可以拨打{{1}}。

答案 1 :(得分:0)

我会在组件中保留API调用,并在调用完成后调度操作。这样,您在configureStore中没有任何副作用,并且可以向用户提供有关当前进度的反馈(例如,通过显示加载微调器)

相关问题