在本代码中,我使用react-redux和react-router。react-redux版本很旧,但我想知道我在这段代码中哪里出错了(我指的是react-redux和react-router的这个版本)。我尝试在main.jsx中获取ingredients,并在OrderSummaryComponent中使用它,但我得到了以下错误:
- 无法读取未定义的属性,
- 未找到状态。
main.jsx:
import ReactDOM from "react-dom/client";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import { Provider } from "react-redux";
import { createStore } from "redux";
import reducer from "./store/reducer";
export default function Main(props) {
const store = createStore(
reducer /* preloadedState, */,
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);
return (
<Provider store={store}>
<BrowserRouter>
<Routes>
<Route path="/" element={<Layout />}>
<Route index element={<App />} />
<Route
path="/burger-builder/order-page"
exact
element={
<OrderSummary
ingredients={props.ingredients}
totalPrice={props.totalPrice}
/>
}
/>
<Route path="*" element={<NoPage />} />
</Route>
</Routes>
</BrowserRouter>
</Provider>
);
}
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<Main />);
BurgerBuilder.jsx:
import * as actionTypes from "../../store/action";
import { connect } from "react-redux";
function BurgerBuilder(props) {
return (
<>
<Burger ingredients={props.ings} />
<BurgerControls
addIngredients={props.onIngredientAdded}
removeIngredients={props.onIngredientRemoved}
totalprice={props.totalPrice}
disabled={disableButton}
/>
</>
);
}
const mapStateToProps = (state) => {
return {
ings: state.ingredients,
price: state.totalPrice,
};
};
const mapDispatchToProps = (dispatch) => {
return {
onIngredientAdded: (ingName) =>
dispatch({ type: actionTypes.ADD_INGREDIENT, ingredientName: ingName }),
onIngredientRemoved: (ingName) =>
dispatch({
type: actionTypes.REMOVE_INGREDIENT,
ingredientName: ingName,
}),
};
};
export default connect(mapStateToProps, mapDispatchToProps)(BurgerBuilder);
- 部分 *
reducer.js:
const reducer = (state = initialState, action) => {
switch (action.type) {
case actionTypes.ADD_INGREDIENT:
return {
...state,
ingredients: {
...state.ingredients,
[action.ingredienName]: state.ingredients[action.ingredientName] + 1
},
totalPrice: state.totalPrice + INGREDIENT_PRICES[action.ingredientName]
};
1条答案
按热度按时间mspsb9vt1#
在
Main
组件中,将props.ingredients
和props.totalPrice
传递给OrderSummary
,但Main
中没有定义props
--当使用root.render(<Main />);
呈现Main
时,不会传递任何props
。为了解决这个问题,你可以像使用
BurgerBuilder
一样将OrderStatus
连接到Redux商店:然后,在
Main
中,渲染不带props
的OrderSummary
:还有你的减速器上有个印刷错误在
ADD_INGREDIENT
的情况下,您编写了action.ingredienName
而不是action.ingredientName
。下面是固定的reducer.js: