【问题标题】:React/Redux - Not dispatching actionReact/Redux - 不调度动作
【发布时间】:2018-04-24 22:12:47
【问题描述】:

我是反应 redux 的新手。我正在尝试使用foursquare api构建一个简单的餐厅应用程序。我有两个动作使 api 调用第一个。搜索餐厅和第二家以获取此类详细信息。

Action.js

export const fetchVenueDetail = venueId => dispatch => {
  console.log("dispatching");
  dispatch({ type: FETCH_VENUE_REQUESTED });
  fetch(
    `https://api.foursquare.com/v2/venues/${venueId}? 
     client_id=${api_id}&client_secret=${api_key}&v=20180422`
  )
    .then(res => res.json())
    .then(data => dispatch({ type: FETCH_VENUE, payload: 
     data.response.venue }))
    .catch(err => console.log(err));
};

这是我的组件

class VenueDetail extends Component {
  componentDidMount() {
    this.props.fetchVenueDetail(this.props.match.params.id);
  }
  render() {
    console.log(this.props);
    const { venue, isLoading } = this.props;
    console.log("This text", venue);
    return (
      <React.Fragment>
        <Header type="venueDetail" venueDetail={venue} />
        <main className="main-content">
          <section className="venue">
            { !isLoading ? <ImageList venueDetail={venue} /> : <Loader /> }
          </section>
          <div className="sidebar-wrapper">
            <Sidebar type="tips" venueDetail={venue} />
          </div>
        </main>
      </React.Fragment>
    )
  }
};

const mapStateToProps = state => ({
  venue: state.venueReducer.venue,
  isLoading: state.venueReducer.isLoading
})

export default connect(mapStateToProps, {fetchVenueDetail})(VenueDetail);

经过测试,我发现它没有发送操作,这就是我收到空响应的原因。

这是工作沙箱代码如果有人想检查-https://codesandbox.io/s/7m4153p1jq

【问题讨论】:

  • 沙盒中似乎有错误。
  • 您的第一个操作dispatch({ type: FETCH_VENUE_REQUESTED }) 没有有效负载
  • @jacob 是的,当我单击第一次操作后收到的场地以获取场地的详细信息时,这就是我遇到的错误。
  • @andrew 该操作仅用于检查 isLoading。我不知道要在有效负载中添加什么,这就是我保留它的原因。
  • @MontyGoldy,它无法识别沙盒上的 redux devtools。这就是那件作品的问题

标签: reactjs redux react-redux


【解决方案1】:

实际问题是,在Sidebar 组件中开始您的请求之前,您会遇到错误。在您的请求完成之前,您的 venue 对象中没有 groups 属性。

如果您在 "tips" 案例中添加此类检查,它应该运行良好:

const itemTips = venueTips.tips.groups ? venueTips.tips.groups[0].items : []; 

您可以将groups 添加到您的reducer 并检查length 属性或选择其他方式,例如包装所有组件,包括Sidebar 组件,并显示Loader 而不是它们。像这样的:

VenueDetail.js

{
    (!isLoading && venue.id) ?
        <React.Fragment>
            <section className="venue">
                <ImageList venueDetail={venue}/>
            </section>
            <div className="sidebar-wrapper">
                <Sidebar type="tips" venueDetail={venue}/>
            </div>
        </React.Fragment> : <Loader/>
}

Here 已更新代码框。

【讨论】:

    【解决方案2】:

    好的,所以问题是我在 componentDidMount 生命周期内调度我的操作,但是当我将它改回 componentWillMount 时。有用。谁能解释一下原因?

    【讨论】:

      猜你喜欢
      • 2021-10-14
      • 2018-05-21
      • 1970-01-01
      • 1970-01-01
      • 2019-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多