【发布时间】:2019-10-15 02:30:55
【问题描述】:
我正在尝试使用 redux 更新 react 状态的值。为了获取我正在使用 axios 的数据,但我们没有返回和更新数据。当我使用 redux 工具检查状态时,状态仍然是初始状态的空列表。
这里是来自 src/action/feedbacks.js。这里使用axios返回json格式的数据
import axios from "axios";
import { GET_FEEDBACKS } from "./types";
export const getFeedbacks = () => dispatch => {
console.log(axios.get("/api/feedbacks/").res.data);
axios
.get("/api/feedbacks/")
.then(res => {
dispatch({
type: GET_FEEDBACKS,
payload: res.data
});
})
.catch(err => console.log(err));
};
此代码来自 src/reducers/feedbacks.js。
import { GET_FEEDBACKS } from "../actions/types.js";
const initialState = {
feedbacks: []
};
export default function(state = initialState, action) {
switch (action.type) {
case GET_FEEDBACKS:
return {
...state,
feedbacks: action.payload
};
default:
return state;
}
}
此代码来自 src/components/feedbacks/Feedbacks.js
import React, { Component, Fragment } from "react";
import { connect } from "react-redux";
import PropTypes from "prop-types";
import { getFeedbacks } from "../../actions/feedbacks";
export class Feedbacks extends Component {
static propTypes = {
feedbacks: PropTypes.array.isRequired
};
ComponentDidMount() {
this.props.getFeedbacks();
}
render() {
return (
//some return code
);
}
}
const mapStateToProps = state => ({
feedbacks: state.feedbacks.feedbacks
});
export default connect(
mapStateToProps,
{ getFeedbacks }
)(Feedbacks);
【问题讨论】:
-
函数被称为
componentDidMount,而不是ComponentDidMount。简单的调试会显示您的操作没有被分派。
标签: javascript reactjs react-redux axios react-proptypes