为什么不能从redux读取我的属性属性
我制作了一个ReactJS和redux应用程序,用于实际操作和处理redux动作,但是当我运行代码时,react表示未定义属性。我尝试调整initState和index.js文件。如果您想要完整的文件,请使用链接https://codesandbox.io/s/landing-page-forked-rkq6f?file=/src/reducers/initState.js,然后在小型浏览器rkq6f.csb.app/search/1
中键入此文件index.js
import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter } from "react-router-dom";
import { ThemeProvider } from "styled-components";
import { theme } from "./Components/UI";
import App from "./App";
import { Provider } from "react-redux";
import { StoreReducer } from "./reducers/reducer";
// reducers
import thunk from "redux-thunk"
import logger from "redux-logger"
import { createStore,applyMiddleware } from "redux"
const store = createStore(StoreReducer,applyMiddleware(thunk,logger))
console.log(store)
ReactDOM.render(
<Provider store={store}>
<BrowserRouter>
<App />
</BrowserRouter>
</Provider>,
document.getElementById("root")
);
initState.js
const initState = {
properties: [],
loading: false,
error: false
};
export default initState;
reducer.js
import initState from "./initState";
export const StoreReducer = (state = initState, action) => {
...
}
};
答案 0 :(得分:1)
问题是您的减速器未返回默认状态,
import initState from "./initState";
export const StoreReducer = (state = initState, action) => {
switch (action.type) {
case "LOADING_PROPERTIES":
// Update total price of cart items
// Subtract item base price + item quantity
return {
...state,
loading: true
};
case "FETCH_PROPERTIES":
// Update total price of cart items
// Subtract item base price + item quantity
return {
...state,
properties: action.payload,
loading: false
};
case "FETCH_PROPERTIES_ERROR":
// Update total price of cart items
// Subtract item base price + item quantity
return {
...state,
loading: false,
error: true
};
/* this ONe */
default:
null;
}
};
您什么都不会退回。
默认情况下,reducer需要返回初始状态
这是工作减速器:
import initState from "./initState";
export const StoreReducer = (state = initState, action) => {
switch (action.type) {
case "LOADING_PROPERTIES":
// Update total price of cart items
// Subtract item base price + item quantity
return {
...state,
loading: true
};
case "FETCH_PROPERTIES":
// Update total price of cart items
// Subtract item base price + item quantity
return {
...state,
properties: action.payload,
loading: false
};
case "FETCH_PROPERTIES_ERROR":
// Update total price of cart items
// Subtract item base price + item quantity
return {
...state,
loading: false,
error: true
};
default:
return initState;
}
};