繁体   English   中英

如何在 redux 中导出存储?

[英]How to export store in redux?

我是新来的反应和 redux ......所以请原谅我的新手错误。 我阅读了 redux 的几个文档并得出结论,这就是我应该如何存储反应组件的 state 的方式。 我需要 redux 因为有更多的嵌套组件需要快速访问数据。 但是...当我尝试导出商店时...我找不到该怎么做。

我的 App.js

export default class App extends Component {
  state = {
    xx: null,
    yy: null
  }
  componentDidMount(){
      //some logic
    // State gets data from api
    this.setState({
      xx: someval,
      yy: someval2
    });
  }
  render() {
    const obj = {
      xx: this.state.xx,
      yy: this.state.yy
    };

    userReducer(obj,updateUserDetails());

    const store = createStore(userReducer);

    return (
      <Provider store={store} >
        <UserDetails props ={this.state} />
      </Provider>
    );
  }
}

// Reducer function
export const userReducer = (state, action) => {
  console.log("in reducer " + JSON.stringify(state));

  switch(action.type) {
    case 'UPDATE_USER_INFO':
      state = {
        ...state,
        xx: action.payload.xx,
        yy: action.payload.yy
      }
      break;
  }

  return state;
}

// Doesn't work
export const store = createStore(userReducer)

// Action
export const updateUserDetails = () => {
  return {
    type: 'UPDATE_USER_INFO'
  }
}

我不知道如何导出存储以便嵌套组件可以访问它。 请帮助提前谢谢!

通过查看您的代码,我可以看到一些问题,每个问题都可能是您的问题。

在减速器首次加载时,它必须保持 state 的初始值,与您要在组件安装时设置的值无关


    // assiging empty obj as initial value
   export const userReducer = (state = {}, action)

redux 的动作是高阶函数,返回要调度的 object


export const updateUserDetails = () => (dispatch, getState) => {
 return dispatch ({
  type: 'UPDATE_USER_INFO'
 })

}


关于您的createStore ,请在此处声明初始值


 // assign empty obj as initial value
export const store = createStore(userReducer, {})

希望对您有所帮助,无论如何我建议再次查看文档

暂无
暂无

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

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