如何在React / Redux中获取并传递对象(JSON API)?

时间:2017-06-02 07:58:04

标签: json reactjs redux react-router react-redux

我有一个问题,从React“Container”中的Store获取并传递JSON对象(info)到他的子组件(InfoPage)通过props .. 我也有Action和Reducer的方法,所有这些都没有错误。 有人可以帮我这个吗? 这是我的“容器”代码。 感谢。

len(lst) % 2 == 0 and lst[:len(lst)//2] == lst[len(lst)//2:]
function mapStateToProps(state) {
  return {
    user: state.auth.user,
    info: state.info,
    ui: state.ui
  };
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators(Object.assign({}, uiActions,
    authActions, infoActions), dispatch);
}

class Info extends Component {

  static propTypes = {
    user: PropTypes.objectOf(PropTypes.any).isRequired,
    ui: PropTypes.objectOf(PropTypes.any).isRequired,
    info: PropTypes.objectOf(PropTypes.any).isRequired,
    switchProfileMenu: PropTypes.func.isRequired,
    logOut: PropTypes.func.isRequired,
  };

  constructor(props) {
    super(props);
    this.handleClickOption = this.handleClickOption.bind(this);
  }

  handleClickOption() {
    return this.props;
  }
  
  render() {
    const { user, logOut, info, ui: { showProfileMenu },
      switchProfileMenu } = this.props;

    return (
      <div className={b()}>
        <Header
          user={user}
          logOut={logOut}
          switchMenu={switchProfileMenu}
          showMenu={showProfileMenu}
        />
        <div className="container">
          <div className="content">
            <div>
              <InfoPage data={info} />
              sadasd
            </div>
          </div>
        </div>
        <Footer />
      </div>
    );
  }

1 个答案:

答案 0 :(得分:0)

我看了你的代码,但有一些缺失的部分。

首先,函数getInfo看起来像是一个thunk(redux-thunk,它允许你执行异步操作)。你必须在索引中导入它并初始化它,而不是数组

import thunk from 'redux-thunk'
// ...
createStore(rooReducer, applyMiddlewares(thunk))

您现在可以用简单的方式定义mapDispatchToProps

import getInfo from './actions'
//  ....
function mapDispatchToProps (dispatch) {
  return {
    dispatchGetInfo(id) {
      dispatch(getInfo(id))
    }
  }
}

在您的组件信息中,实现如下:

componentDidMount () {
  const { dispatchGetInfo, params: { id } } = this.props
  // I PRESUME your `id` is inside the params of react router, feel free to change if not
  dispatchGetInfo(id) // => this should call your thunk which will call your consecutive dispatcher
}

修改

您的索引文件应包含此修改后的行

<Route name="app:info" path="information/:id" component={Info} />