繁体   English   中英

在React中填充初始状态

[英]Populating Initial State in React

我是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);

然后,我需要将此状态传递给我的单个减速器,就像这样。

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

    default:
      return state;
  }
}

我似乎找不到正确的方法来做到这一点。 如果有人可以就如何将api调用从组件中移出,在存储中进行调用,设置初始状态然后将其传递回组件,我会非常感激。 提前致谢。

我牢记在心的redux概念之一是:

不管采取什么行动,都会采取行动来更新商店(获取数据,调用chrome API等)

让我们在您的案例中尝试一下这个概念:

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);

    // once you have the new user.
    // time to update the store.
    dispatch({
      type: 'UPDATE_STORE_WITH_NEW_USER'
      payload: {
        user: newUser,
      },
    });
  });

下一个问题是,如何获得dispatch功能。 一种方法是导入实例化的存储,然后像这样调用调度函数:

import store from 'path/to/store';

store.dispatch({ type: 'ACTION_TO_BE_DISPATCHED' });

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

介绍redux-thunk 请参阅此处以了解为什么需要此功能。 使用redux-thunk ,您可以创建如下操作:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM