【问题标题】:TypeError when use the React hooks- useReducer使用 React 钩子时的 TypeError-useReducer
【发布时间】:2018-11-21 04:47:59
【问题描述】:

我尝试使用反应钩子(useReducer)。我有错误

TypeError: Object(...) 不是函数

这里我附上了我的代码并附上了错误截图。

import React, { useReducer } from 'react';

function appReducer(state, action){
    switch(action.type){
        case 'add':
            return [
                ...state,
                {
                    id:Date.now(),
                    text:'',
                    completed:false
                }
            ]
        break;
        default:
        break;
    }
}

export default function myCom(){
    const [state, dispatch] = useReducer(appReducer, []);
    return (
        <div className="App">
            <h5>React ToDo</h5>
            <button onClick={() => dispatch({type:'add'})}>New Todo</button>
            {
                state.map(item =>(
                    <div key={item.id}>{item.id}</div>
                ))
            }
        </div>
    );
}]

如何解决此错误。

【问题讨论】:

  • 你如何渲染 myCom

标签: javascript reactjs react-hooks


【解决方案1】:

错误不是 useReducer 而是你错误地使用了导出默认值:

export default function myCom(){

如果你想导出命名函数,那么你可以这样做:

// function definition
function myComp() {}
// then export
export default { myComp }

然后你可以像这样使用:

import Something from '...'
Something.myComp()

但是,如果您只想导出一个函数,那么我将这样做:

export const myComp = () => {}

现在,您可以像这样导入:

import { myComp } from '...'
myComp()

【讨论】:

  • 我试过在你的回答中最后提到你。我仍然有同样的错误。你可以在这里找到代码jsfiddle.net/wv1ae28k
  • 啊,我的错。写了点别的。已更新。
猜你喜欢
  • 2019-12-09
  • 1970-01-01
  • 2022-01-17
  • 2021-05-15
  • 2021-05-10
  • 1970-01-01
  • 1970-01-01
  • 2020-04-30
  • 2020-04-04
相关资源
最近更新 更多