import React, { useState, PropsWithChildren } from "react" interface AppStateValue { username: string shoppingCart: { id: number; name: string }[] } const defaultContextValue: AppStateValue = { username: "JOKER", shoppingCart: [], } export const appContext = React.createContext(defaultContextValue) export const appSetStateContext = React.createContext< React.Dispatch<React.SetStateAction<AppStateValue>> | undefined >(undefined) export const DemoStateProvider: React.FC<PropsWithChildren<{}>> = props => { const [state, setState] = useState(defaultContextValue) return ( <appContext.Provider value={state}> <appSetStateContext.Provider value={setState}> {props.children} </appSetStateContext.Provider> </appContext.Provider> ) } import React, { useContext } from "react" import styles from "./Robot.module.css" import { appContext, appSetStateContext } from "../demoState" interface RobotProps { id: number name: string email: string } const Robot: React.FC<RobotProps> = ({ id, name, email }) => { const value = useContext(appContext) const setState = useContext(appSetStateContext) const addToCart = () => { console.log(setState, "@@") if (setState) { // 思考: 同学们可以想一想如何化简这里的代码 setState(state => { console.log(state, "??") return { ...state, shoppingCart: [...state.shoppingCart, { id, name }], } }) } } return ( <div className={styles.cardContainer}> <img alt='robot' src={`https://robohash.org/${id}`} /> <h2>{name}</h2> <p>{email}</p> <p>作者:{value.username}</p> <button onClick={addToCart}>加入购物车</button> </div> ) } export default Robot console.log(setState, "@@") 为什么这里式undefined
时间: 2024-03-11 14:45:37 浏览: 125
这里的`setState`是在函数组件中使用`useContext`从`appSetStateContext`上下文中获取的。如果在组件树中没有提供`appSetStateContext`的上下文,那么`setState`就会是`undefined`。通常情况下,这种情况会发生在组件树的根节点处没有提供`appSetStateContext`的情况下。
阅读全文