当我尝试在反应中使用useReducer挂钩时出现问题

时间:2020-07-15 13:38:44

标签: javascript reactjs

这是我的代码

import React, {createContext, useContext, useReducer } from 'react';

// this is data layer
export const StateContext = createContext();

//  build a provider
export const StateProvider = ({ reducer, initialState, children}) => {
    
    <StateContext.Provider value={useReducer(reducer, initialState)}>
        {children}
    </StateContext.Provider>
};

但是当我运行应用程序时出现此错误

无法编译。

./ src / StateProvider.js 第9:5行:需要执行赋值或函数调用,而是看到一个表达式no-unused-expressions

搜索关键字以详细了解每个错误。

2 个答案:

答案 0 :(得分:0)

似乎您不是从StateProvider功能组件返回。 将您的StateProvider声明替换为

    export const StateProvider = ({ reducer, initialState, children}) => (
        <StateContext.Provider value={useReducer(reducer, initialState)}>
            {children}
        </StateContext.Provider>
    )

(通知{ }替换为( )


    export const StateProvider = ({ reducer, initialState, children}) => {
        return (
            <StateContext.Provider value={useReducer(reducer, initialState)}>
                {children}
            </StateContext.Provider>
        )
    }

答案 1 :(得分:0)

<StateProvider />不是有效的React组件,因为它没有返回任何React元素。都是关于JSX和箭头函数的东西。错误消息还会为您提供此提示。

(param1, param2, …, paramN) => { statements } 
(param1, param2, …, paramN) => expression
// equivalent to: => { return expression; }

// Parenthesize the body of a function to return an object literal expression:
params => ({foo: bar}) 

在您的情况下,StateProvider什么也不返回。

制作:

export const StateProvider = ({ reducer, initialState, children}) => (
        <StateContext.Provider value={useReducer(reducer, initialState)}>
            {children}
        </StateContext.Provider>
)