首页 > 解决方案 > React-Redux / useSelector hook 和 Provider 给我一些问题

问题描述

好的,我又来了。我开始在我用 TypeScript 编写的 React App 中实现一个 Redux 存储,并尝试了解 react 如何与 redux 一起工作。

所以也许它很容易,也许不是。我有一家商店,好吧,那是一个全局单一对象(我猜是单一对象)。所以这个对象可以包含我所有的状态。这种状态可以是具有单个值的对象,也可以是其中包含数组的对象。

我不明白的是useSelector Hook。

我有这个组件:

export const ShoppingCartComponent = () => {
    const totalPrice = useSelector(state => state.totalPriceOfAllProducts)

    return <>(
        <Accordion defaultActiveKey="0" className={"shoppingCart"}>
            <Card>
                <Accordion.Toggle as={Card.Header} eventKey="0">
                    Click me!
                </Accordion.Toggle>
                <Accordion.Collapse eventKey="0">
                        <Card.Body>
                            {totalPrice}
                        </Card.Body>
                </Accordion.Collapse>
            </Card>
        </Accordion>
    )</>
}

所以 useSelector 钩子接受一个 selectorFunction 并与整个 redux 存储一起调用。那是对的吗?

也许我不明白。我是否需要实现自定义 selectorFunction,然后将其作为参数传递?

因为在我找到的材料中,它看起来很简单:

const someValue = useSelector(state => state.theValueWhatIWant)

我使用 ReduxToolkit 是因为 redux 团队自己推荐使用它。

React 给了我这个我不明白的错误:

Error: Objects are not valid as a React child (found: object with keys {}). If you meant to render a collection of children, use an array instead.
./src/index.tsx/<
F:/Workspaces/Frontend/testreact_ts/src/index.tsx:10

   7 | import store from "./store/store";
   8 | import {Provider} from "react-redux";
   9 | 
> 10 | ReactDOM.render(
  11 |     <Provider store={store}>
  12 |         <BrowserRouter>
  13 |           <React.StrictMode>

但我需要提供者对吗?它甚至说我,那是整个商店,没关系,但商店当然是一个对象。现在我不允许将该对象作为提供者传递?

商店看起来像这样:

import {configureStore} from '@reduxjs/toolkit'
import {totalPriceOfAllProductsReducer} from "./features/totalPriceOfAllProductsSlice";
import {productsInShoppingCartReducer} from "./features/productsInShoppingCart";

export default configureStore({
    reducer: {
        totalPriceOfAllProductsReducer,
        productsInShoppingCartReducer,
    }
})

再次感谢任何帮助 :-)

祝你今天过得愉快

编辑:我再次创建了一个沙箱:https ://codesandbox.io/s/react-redux-store-question-ghmm3

标签: reactjsreduxreact-reduxredux-toolkit

解决方案


推荐阅读