【发布时间】:2017-06-03 13:12:46
【问题描述】:
编辑:我已经将我的返回更改为一个对象,但我仍然得到空道具。
mapStateToProps(state) 的console.log 显示温度为空。我假设我正在恢复一个未更改的状态,我的 axios 调用的温度没有返回到我的weatherPage.js。
我的整个环境运行良好,我只是想发出一个 axios 获取请求。
我在通过 Redux 生命周期传递我的对象时遇到了一点困难,从动作到减速器,同时保持 propTypes 验证方法并尝试使用 Object.assign()(这确实是正确的变异方式Dan Abramov 指出的具有单个深层副本的状态。)
错误:
我的道具是空的。我在 src/actions/weatherActions.js 中进行的 axios 调用未在 src/components/weatherPage.js 中显示为 prop.weatherDetails.temperature
,它返回我的默认状态。
- 我是 ES6 和 Redux 的新手,我已将 propTypes 包含到我的页面中,对此我有一点问题,我认为问题在于提供来自操作的正确状态。李>
- 当按下选择按钮时,我应该会收到 temp_c(axios 调用 this json)
src/components/weatherPage.js
import React, {PropTypes} from 'react';
import {connect} from 'react-redux';
import {withRouter} from 'react-router';
import * as WeatherActions from '../../actions/weatherActions';
class WeatherPage extends React.Component {
render() {
return (
<div>
<h2>temps: {this.props.weatherDetails.temperature}</h2>
<input
type="submit"
onClick={this.onClickSave.bind(this)}
value="CHOOSE"/>
</div>
);
}
onClickSave() {
WeatherActions.getWeather(this.props.dispatch);
}
WeatherPage.propTypes = {
weatherDetails: PropTypes.object.isRequired,
dispatch: PropTypes.func.isRequired
};
function mapStateToProps(state) {
return {
weatherDetails: state.weathers.weatherDetails
};
}
export default connect(mapStateToProps)(withRouter(WeatherPage));
- 由于
this.props.weatherDetails.temperature显示了我的当前状态,我知道问题出在操作和reducer 之间。
src/actions/weatherActions.js
import axios from 'axios';
export const ActionTypes = {
WEATHER: { LOAD_WEATHER: 'WEATHER.LOAD_WEATHER' } };
export function getWeather(dispatch) {
console.log('in getWeather method');
console.log('this is getWeather dispatch: ', dispatch);
axios({
url: 'http://api.weatherunlocked.com/api/trigger/32.08,34.78/current%20temperature%20gt%2016%20includecurrent?app_id=ba2f68f0&app_key=0356747cc4d1d4ba0dd5cc25a0c86743',
method: 'get'
}).then(function (response) {
//console.log('in the then func with this res: ', JSON.stringify(response));
dispatch({
type: ActionTypes.WEATHER.LOAD_WEATHER,
temperature: response.CurrentWeather.temp_c
},
function () {
console.log('dispatch completed');
});
});
console.log('end of class getWeather');
- 我正在执行一个简单的 axios 调用,但我不确定我是否正确地调度了 'payload' (
temperature: response.CurrentWeather.temp_c) 以通过减速器出现并返回到视图中。
这是我的减速器:
src/reducers/weatherReducer.js
import * as WeatherActions from '../actions/weatherActions';
const initialState = {
weatherDetails: {
area: '',
temperature: 'sdf'
}
};
function WeatherReducer(state = initialState, action) {
console.log('in WeatherReducer, this is action: ' + JSON.stringify(action));
switch (action.type) {
case WeatherActions.ActionTypes.WEATHER.LOAD_WEATHER:
return [...state, Object.assign({}, action.temperature.data)];
default:
return state;
}
}
export default WeatherReducer;
我在这个版本中缺少什么?
【问题讨论】:
-
这是问题(数组,不是对象):
return [...state, Object.assign({}, action.temperature.data)]; -
@wesley6j 你会怎么写? Shubham Khatri 尝试过,但这是一个错误。
标签: reactjs react-redux