我是redux的新手,我已经阅读了有关此主题的其他问题。我已经尝试过,并在这一点上已经寻找了一段时间。我在和chrome中使用了Redux开发工具,可以看到我的操作提取了我需要的信息,但是并没有达到状态。这是我的一些代码,任何帮助将不胜感激。
actions.js
export const FETCH_DATA = {
FETCH_DATA_BEGIN: "FETCH_DATA_BEGIN",
FETCH_DATA_SUCCESS: "FETCH_DATA_SUCCESS",
FETCH_DATA_FAILURE: "FETCH_DATA_FAILURE",
};
export const fetchDataBegin = () => ({
type: FETCH_DATA.FETCH_DATA_BEGIN,
});
export const fetchDataSuccess = (data) => ({
type: FETCH_DATA.FETCH_DATA_SUCCESS,
payload: data,
});
Reducers.js
import { FETCH_DATA } from "./actions";
const initialState = {
data: [],
loading: false,
error: null,
};
export default function displayDataReducer(state = initialState, action) {
switch (action.type) {
case FETCH_DATA.FETCH_DATA_BEGIN:
return {
...state,
loading: true,
error: null,
};
//Sets the data
case FETCH_DATA.FETCH_DATA_SUCCESS:
return {
...state,
loading: false,
data: action.payload.data,
};
我的商店/index.js
import { createStore, combineReducers, applyMiddleware, compose } from "redux";
import thunk from "redux-thunk";
import displayDataReducer from "./displayData/reducer";
// The Dev Tool extension for the browser
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
// export const RootReducer = combineReducers({
// data: displayDataReducer,
// });
export default createStore(
displayDataReducer,
composeEnhancers(applyMiddleware(thunk))
);
我的组件
import React, { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import axios from "axios";
import Navbar from "../brand/Navbar";
import Masthead from "../brand/Masthead";
import Footer from "../brand/Footer";
import MainContent from "../content/MainContent";
function App() {
const content = useSelector((state) => state);
const dispatch = useDispatch();
function getData() {
return (dispatch) => {
axios.get("https://jsonplaceholder.typicode.com/todos/1").then((res) =>
dispatch({
type: "FETCH_DATA.FETCH_DATA_SUCCESS",
data: res.data,
})
);
};
}
useEffect(() => {
dispatch(getData());
}, []);
答案 0 :(得分:1)
问题::type: "FETCH_DATA.FETCH_DATA_SUCCESS"
应该只是type: "FETCH_DATA_SUCCESS"
,或者您并不是故意要在其周围加上引号,在这种情况下,您还需要导入{{ 1}}。
FETCH_DATA
OR
import React, { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import axios from "axios";
import Navbar from "../brand/Navbar";
import Masthead from "../brand/Masthead";
import Footer from "../brand/Footer";
import MainContent from "../content/MainContent";
function App() {
const content = useSelector((state) => state);
const dispatch = useDispatch();
function getData() {
return (dispatch) => {
axios.get("https://jsonplaceholder.typicode.com/todos/1").then((res) =>
dispatch({
type: "FETCH_DATA_SUCCESS", // <-- Drop the prefix
data: res.data,
})
);
};
}