【问题标题】:Redux container cannot display the reducer handling an API callRedux 容器无法显示处理 API 调用的 reducer
【发布时间】:2019-01-21 04:55:21
【问题描述】:

我一直在使用 React、Redux、Redux-promise 和 Axios 构建一个基本的天气应用程序(使用 openweathermap.org 处理当前天气的 API)。 如果单击该按钮,则该城市 (Cecciola) 的天气参数应显示在控制台上。
Action 正确地检索了数据,并且由于 Promise,它作为普通的 payload.data 而不是 Promise 传递给 reducer。
然后,负责渲染 city.name 的容器连接到管理天气的 reducer(以便您可以使用 this.props 访问它),但如果单击按钮,console.log(this.props. tempo....) 表示对象未定义。为什么?

GitHub Repo link

【问题讨论】:

    标签: javascript html api redux


    【解决方案1】:

    尝试您的存储库,登录到控制台 this.props.tempoceciola 组件的渲染方法中对我来说效果很好。

    我看到错误的地方是您的renderR() 函数。您正在尝试使用diocane.city.name,但该对象没有“城市”属性。

    尝试:<p>{diocane.name}</p> 获取名称。

    _______ 更新 ________

    回复您的评论:我从存储库中提取了最新版本,当您单击按钮检索数据时,一切似乎都正常工作。就像现在的代码一样,你正在做:

    console.log(this.props.tempo[0])

    因此,在第一次加载组件时,props.tempo 数组中没有任何内容,因此您会在控制台中看到 undefined。当您单击按钮时,您现在在数组中有一个对象,并且该日志语句可以正常工作。

    我将您的render() 方法更改为:

    render() {
        if (this.props.tempo.length > 0) {
          console.log("TEMPO", this.props.tempo[0])
          console.log("ID", this.props.tempo[0].id)
        }
        return (
            <div>
               {this.props.tempo.map(t => {
                 return <div key={t.id}>{t.name}: {t.main.temp} </div>
               })}
            </div>
        );
    }
    

    它会注销预期的信息。在尝试访问它之前,您只需要确认 tempo 属性在数组中有一些东西。然后,当您这样做时,请确保您正在访问内部的单个对象。我在上面的return() 方法中展示了一个示例:使用map 迭代并返回一个带有节奏对象信息的&lt;div&gt; 元素的新数组。

    【讨论】:

    • 嗨!我用新的提交更新了文件夹。现在清楚多了。基本上,在 cecciola.js 中有一个 this.props.tempo 的控制台日志。我可以访问它,但是一旦我尝试访问 tempo 的属性(base、cod、id、name 等),它就会说它是未定义的。为什么?
    猜你喜欢
    • 1970-01-01
    • 2017-05-16
    • 2016-10-12
    • 2017-06-09
    • 2016-05-05
    • 1970-01-01
    • 1970-01-01
    • 2017-04-03
    • 2016-07-21
    相关资源
    最近更新 更多