设置状态时,React上下文API返回未定义

时间:2020-02-04 22:59:30

标签: javascript reactjs react-redux react-hooks react-context

我最近开始学习反应,并且我正在使用上下文api存储我的全局状态。

MyProvider.js 文件中,我定义了提供程序,它仅存储了2个json obj数组

import {MyContext} from "./MyContext";
import React, {useState} from "react";

export const MyProvider = (props) => {
    const intialState = {
        featuredListings: [],
        setFeaturedListings: (val) => setState({...state, featuredListings: val}),
        featuredVendors: [],
        setFeaturedVendors: (val) => setState({...state, featuredVendors: val})
    }

    const [state, setState] = useState(intialState)

    return (
        <MyContext.Provider
            value={state}
        >
            {props.children}
        </MyContext.Provider>
    );
}

我这样做是将所有组件包装在提供程序的 App.js 中,不使用ReachRouter来处理路由,

<MyProvider>
    <div className="content">
        <Header/>
        <Router>
            <Home path="/"/>
        </Router>
    </div>
    <Footer />
</MyProvider>

在我的 Home.js 文件中,我在useEffect钩子中进行了网络调用,该钩子成功返回了我期望的json,并使用该json响应更新了上下文的状态,以便可以全局可见。

我的代码是

export const Home = () => {
    let state = useContext(MyContext)

    async function apiCalls() {
        const featuredVendors = await getFeaturedVendors()
        console.log("featuredVendors - ", featuredVendors) // the correct response is returned
        state.setFeaturedVendors(featuredVendors)

        const featuredListings = await getFeaturedListing()
        console.log("featuredListings - ", featuredListings) // the correct response is returned
        state.setFeaturedListings(featuredListings)
    }

    useEffect(() => {
        apiCalls()
    }, []);

    return (
        <div>
            {console.log(state.featuredVendors)}  // empty array
            {console.log(state.featuredListings)} // contains correct values
        </div>
    )
}

]

要消除任何歧义,我的上下文是在名为 MyContext.js 的单独文件中创建的 然后像这样创建Context

export const MyContext = React.createContext()

为什么设置时 state.featuredVendors 不更新?

我注意到的另一件奇怪的事情是,如果我重新安排电话的顺序,即 getFeaturedListing 首先是 getFeaturedVendors ,然后我的状态仅是FeaturedVendors的更新,featuredListings将是一个空数组。

1 个答案:

答案 0 :(得分:1)

调用useState时,initialValue仅设置一次。首次安装MyProvider时,状态将用setFeaturedListingssetFeaturedVendors方法初始化,但是只要state的值更改,这些方法就不会更新。因此,state的值在散布时将始终是其初始值。

setState也可以通过始终接收当前值作为参数的函数来调用,因此您可以重写这些方法以扩展该值,如下所示:

    const intialState = {
        featuredListings: [],
        setFeaturedListings: (val) => setState(state => ({...state, featuredListings: val})),
        featuredVendors: [],
        setFeaturedVendors: (val) => setState(state => ({...state, featuredVendors: val}))
    }

或者,您也可以将这些功能完全移到您的状态之外。

export const MyProvider = (props) => {
  const intialState = {
      featuredListings: [],
      featuredVendors: [],
  }
  const [state, setState] = useState(intialState)
  return (
      <MyContext.Provider
          value={{
            ...state,
            setFeaturedListings: (val) => setState({...state, featuredListings: val}),
            setFeaturedVendors: (val) => setState({...state, featuredVendors: val})
          }}
      >
          {props.children}
      </MyContext.Provider>
  );
}