javascript - 引用错误 : Dispatch is not defined

标签 javascript reactjs react-redux redux-thunk

我有一个连接器,它具有 mapDispatchToProps 和 mapStateToProps 函数,我需要从我的主要组件分派(dispatch)一个 Action 。

当我尝试调度 fetchPlaces(this.props.user.id)

时,我收到一条错误消息,提示 dispatch is not defined

this.props.user.id 的值为 1。

我需要获取用户 ID 并将其传递给 fetchPlaces,该实习生会为我获取用户的位置。我不确定该怎么做。

连接器

const mapStateToProps = function (store) {
    return {
        elements: store.elements.elements,
        places: store.places.places,
        geocode : store.geocode.geocode,
        user : store.user.user
    };
};

const mapDispatchToProps = function (dispatch) {
    return {
        userAction : dispatch(fetchUser()),
        elementsAction : dispatch(fetchCategories()),
        placesAction: (id) => { dispatch(fetchPlaces(id)) }        
    }
}

class BasicinfoConnector extends React.Component{
  render() {
      console.log(this.props.user);
      if(typeof this.props.user.id != "undefined"){
          return (
              <Basicinfo elements={this.props.elements} places={this.props.places} geocode={this.props.geocode} user={this.props.user}/>
          );
      }
      else{
          return null;
      }
  }
}

export default Redux.connect(mapStateToProps, mapDispatchToProps)(BasicinfoConnector);

组件:

componentWillMount() {
        console.log(this.props);
        console.log(this.props.user.id);
        dispatch(fetchPlaces(this.props.user.id))
    }

placesAction: (id) => { dispatch(fetchPlaces(id)) } 是正确的语法吗?

更新

我更改了 componentWillMount :

componentWillMount() {
        console.log(this.props);
        console.log(this.props.user.id);
        dispatch(this.props.placesAction(this.props.user.id))
    }

和 mapDispatchToProps :

const mapDispatchToProps = function (dispatch) {
    return {
        userAction: bindActionCreators(fetchUser, dispatch),
        elementsAction: bindActionCreators(fetchUser, dispatch),        
        placesAction: (id) => { dispatch(fetchPlaces(id)) }
    }
}

还是一样的错误

最佳答案

您需要将属性传递到下一个级别,或者像这样共享您的所有 Prop :

<Basicinfo {...this.props} />

或者只有你想要的特定的

<Basicinfo placesAction={(id) => this.props.placesAction(id)} />

关于javascript - 引用错误 : Dispatch is not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41515063/

相关文章:

javascript - React 类组件使用嵌套的 map() 来显示数据

javascript - react native : renderRow not executed

javascript - 飞行前响应中的 Access-Control-Allow-Methods 不允许方法 PATCH

javascript - 在函数内渲染组件 react

ReactJS redux 订阅语句

javascript - 将 JSON 附加到文件上传

javascript - 将 JSON 对象映射到 Javascript 对象

javascript - 如何在React Native中调用Alert onPress并传递一些参数

javascript - $(document).scrollTop() 总是返回 0

javascript - 将 OO 语言编译为 Javascript