【发布时间】:2018-10-05 19:37:10
【问题描述】:
当我在我的 react 组件中 mapStateToProps 时,我对 redux 还很陌生,并且无法解析 JSON 数据。例如,如果我在我的 react 组件中使用 console.log(this.props.chartData[0]),控制台将显示我尝试访问的数组,但是,当我尝试通过控制台访问数组中的特定元素时记录(this.props.ChartData[0].title),我得到一个错误:
[enter image description here][1]
class ChartContainer extends Component {
componentWillMount(){
this.props.chartChanged();
}
render(){
console.log(this.props.chartData[0]);
return(
<Text style={styles.textStyle}>
test
</Text>
);
}
}
const mapStateToProps = state => {
return {
chartData: state.chart
}
};
export default connect (mapStateToProps, {chartChanged}) (ChartContainer);
有趣的是,我在 reducer 中访问(this.props.ChartData[0].title) 没有问题。
import {CHART_CHANGED} from '../actions/types';
const INITIAL_STATE = { chartData: [] };
export default (state = INITIAL_STATE, action) => {
console.log(action);
switch (action.type) {
case CHART_CHANGED:
console.log("action");
console.log(action.payload[0].title);
return{...state, chartData: action.payload};
default:
return state;
}
};
这是我的操作文件中的 api 调用:
export const chartChanged = (chartData) => {
return (dispatch) => {
axios.get('https://rallycoding.herokuapp.com/api/music_albums')
.then((chartData) =>{
dispatch({type: CHART_CHANGED, payload: chartData.data});
});
};
};
如果有人能解释为什么会发生这种情况,我将非常感激。
【问题讨论】:
-
它是否记录了一个空数组?
-
不,它正在记录未定义。
-
您是从 API 获取数据吗?
-
是的,我从 API 获取。
-
你能给我看看这个console.log this.props.ChartData吗?
标签: react-native redux axios redux-thunk