Redux:Call to action-creator返回'无法读取未定义'

时间:2017-07-24 17:17:43

标签: javascript reactjs redux react-redux

我能够获取某个城市的天气,但之后无法知道如何删除它。 作为Redux的新手,我正在努力想象我在这个谜题中缺少哪些碎片。

我将FETCH_WEATHER代码留给上下文提议。我的问题在于DELETE_CITY实现。

错误: enter image description here

步骤:

  • 调用行动创建者的每一行中添加一个按钮。

  • 动作创建者获取“城市”的名称并返回“DELETE_CITY”类型的动作。

  • 缩减器,监视该类型并遍历城市数组并删除具有给定城市名称的对象。

动作创建者

import axios from 'axios';
const API_KEY = '1111111111111111111111';
const ROOT_URL = `http://api.openweathermap.org/data/2.5/forecast?appid=${API_KEY}`;

export const FETCH_WEATHER = 'FETCH_WEATHER';
export const DELETE_CITY = 'DELETE_CITY';

//fetch cities
export function fetchWeather(city){
    const url = `${ROOT_URL}&q=${city},&units=imperial`;
    const request = axios.get(url);
    console.log('Request:', request);

    return {
        type: FETCH_WEATHER,
        payload: request
    }
}

//Delete Cities
export function deleteCity(city) {
    return {
        type: DELETE_CITY,
        payload: city
    }
}

Reducer:index.js

import { combineReducers } from 'redux';
import WeatherReducer from './reducer_weather';

const rootReducer = combineReducers({
  weather: WeatherReducer
});

export default rootReducer;

weather_reducer.js

DELETE_CITY是否准确实施?

import { FETCH_WEATHER } from '../actions/index';
import { DELETE_CITY } from '../actions/index';

export default function (state = [], action) {
    console.log('Action received', action);

    //only fetch weather data type
    switch (action.type) {
        case FETCH_WEATHER:
            //concat to prevent state mutation
            return state.concat([action.payload.data]);

        case DELETE_CITY:
            return state
                .slice(0, action.payload.data)
                .concat([action.payload.data].slice([action.payload.data] + 1));
    }
    return state;
}
  • 在调用动作创建者的每一行中添加一个按钮。

Ps:mapStateToProps和mapDispatchToProps是否正确?

weather_container.js

import React, { Component } from 'react';
import { connect } from 'react-redux';
import Chart from '../components/chart';
import GoogleMap from '../components/google_map';
import { bindActionCreators } from 'redux';
import { deleteCity } from '../actions/index';

class WeatherList extends Component {

    renderWeather(cityData) {
        const name = cityData.city.name;

        return (
            <tr key={name}>
                <td><button onClick={() => this.props.deleteCity(cityData)} className="btn btn-danger">x</button></td>
            </tr>
        )
    }
    render() {
        return (
            <table>
                <thead>
                    <tr>
                        <th>City</th>
                    </tr>
                </thead>
                <tbody>
                {this.props.weather.map(this.renderWeather)}
                </tbody>
            </table>
        )
    }
}

 function mapStateToProps(state) {
     return {
         weather: state.weather
     }
 }

 function mapDispatchToProps(dispatch, weather) {
     return bindActionCreators({deleteCity},{weather}, dispatch)
 }

 export default connect(mapStateToProps, mapDispatchToProps)(WeatherList);

我需要将动作创建器绑定到onClick事件。 我尝试了两种方法:胖箭头函数和/或'绑定构造函数内部的方法()'。

他们都返回道具未定义。

3 个答案:

答案 0 :(得分:3)

尝试替换:

{this.props.weather.map(this.renderWeather)}

使用

{this.props.weather.map(this.renderWeather, this)}

map的第二个参数是thisArg - 在执行this时用作callback的值。

答案 1 :(得分:1)

您需要绑定renderWeather函数。

class WeatherList extends Component {
    constructor(){
        super();
        this.renderWeather = this.renderWeather.bind(this);
    }
    ...
}

答案 2 :(得分:1)

您收到的错误消息cannot read property props of undefined表示this.props this未定义。

这是一个常见的反应,主要是因为它脱离了背景。

您需要做的是将renderWeather函数绑定到构造函数

中的WeatherList
constructor() {
   this.renderWeather = this.renderWeather.bind(this)
}

另一种选择是使用箭头功能

class {
   renderWeather = (weatherData) => {
       ...
   }
   ...
}

删除城市时,您还可以在reducer中考虑此实现。

[...state].filter((weather) => {
    return weather.id != action.payload.data.id
})

.filter()返回符合给定条件的新项目数组