TypeError: list.map 不是一个函数

我正在为 React Practice 构建应用程序,但在尝试将对象数组存储到本地存储时遇到错误。我是 React 的初学者,所以我不确定发生了什么。我在 IncomeOutputList 组件中收到错误,因为我试图使用数组列出一堆对象。


这是我的代码:


应用组件:


import React, { useState, useReducer } from 'react';

   import BudgetInput from './components/input/BudgetInput';

   import IncomeOutputList from './components/output/IncomeOutputList';

   import IncomeOutput from './components/output/IncomeOutput';


const useSemiPersistentState = (key, initialState) => {

  const [value, setValue] = React.useState(

    localStorage.getItem(key) || initialState

  );

  

  React.useEffect(()=>{

    localStorage.setItem(key, JSON.stringify(value));

  }, [value, key])


  return [value, setValue];

};


const App = () => {

  const [incomes, setIncomes] = useSemiPersistentState('income',[{}]);

  const [description, setDescription] = useState('');

  const [type, setType] = useState('+');

  const [value, setValue] = useState('');


  const incomeObj = {

    desc: description,

    budgetType: type,

    incomeValue: value

  }


  const handleIncomeObjArray = () => {

    setIncomes(incomes.concat(incomeObj));

    console.log(incomes + "testing");

  }


  const handleChange = (event) => {  //this handler is called in the child component BudgetInput

    setDescription(event.target.value);

  }


  const handleSelectChange = (event) => {  //this handler is called in the child component BudgetInput

    setType(event.target.value);

  }


  const handleValueChange = (event) => {

    setValue(event.target.value);

    console.log(incomeObj)

  }


  return (

    <div className="App">


      <div className="top">


        

      </div>


      <div className="bottom">

        <BudgetInput 

          descValue={description}

          onDescChange={handleChange}

          onSelectChange={handleSelectChange}

          type={type}

          onBudgetSubmit={handleIncomeObjArray}

          budgetValue={value}

          onValChange={handleValueChange}

        />


        {/* <IncomeOutput 

          obj={incomeObj}

        /> */}



月关宝盒
浏览 154回答 1
1回答

侃侃尔雅

这是因为您的 Custom reducer 返回一个字符串而不是一个数组尝试这个const useSemiPersistentState = (key, initialState) => {&nbsp; const [value, setValue] = React.useState(&nbsp; &nbsp; localStorage.getItem(key) ? JSON.parse(localStorage.getItem(key)) : initialState&nbsp; );&nbsp;&nbsp;&nbsp; React.useEffect(()=>{&nbsp; &nbsp; localStorage.setItem(key, JSON.stringify(value));&nbsp; }, [value, key])&nbsp; return [value, setValue];};
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript