开发者问题收集

无法读取 useEffect 钩子上未定义的属性“map”

2021-07-23
182

我最近开始学习 React,并陷入了上述错误。我知道这个错误有很多答案。是的,我已经看到了这些解决方案,但我无法将这些解决方案映射到我的问题上。我在下面粘贴了我的代码,请告诉我下面的代码有什么问题。任何帮助都非常感谢。谢谢。

const orders = () => {

    const [stateValue, setState] = useState({
        orders: [],
        loading: true
    });

    // getting the orders
    useEffect(() => {
        axiosInstance.get('/orders.json').then(res => {
            transformData(res);
            setState({loading: false});
        }).catch(err => {
            console.log(err)
            setState({loading: false});
        })
    }, []);

    // transforming firebase response(objects of objects) into array of objects
    const transformData = (response) => {

        const ordersData = [];
        if(response.data) {
            for (let key in response.data) {
                ordersData.push({
                    ...response.data[key],
                    id: key
                })
            }
        }

        setState({orders: ordersData});
    }
    
    let orders;
    orders = stateValue.orders.map((order) => <Order //error line
                key={order.id}
                ingredients={order.ingredients} 
                email={order.email}
                price={order.price}
                />); 
        
    if(stateValue.loading) {
        orders = <Loading />
    }

    return(
        <div>
             {orders}
        </div>
       
    )
}
1个回答

useState hook 的 setter 函数 不会像其类等效函数那样合并状态 文档中提到 ):

However, unlike this.setState in a class, updating a state variable always replaces it instead of merging it.

// Merge with prev state in function component
setState(prev => ({...prev, loading: false}))

// In class component, the setter merges state by default
this.setState({loading: false});
Dennis Vash
2021-07-23