为了账号安全,请及时绑定邮箱和手机立即绑定

TypeError: list.map 不是一个函数

TypeError: list.map 不是一个函数

月关宝盒 2023-03-24 14:58:07
我正在为 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}        /> */}
查看完整描述

1 回答

?
侃侃尔雅

TA贡献1801条经验 获得超15个赞

这是因为您的 Custom reducer 返回一个字符串而不是一个数组


尝试这个


const useSemiPersistentState = (key, initialState) => {

  const [value, setValue] = React.useState(

    localStorage.getItem(key) ? JSON.parse(localStorage.getItem(key)) : initialState

  );

  

  React.useEffect(()=>{

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

  }, [value, key])


  return [value, setValue];

};


查看完整回答
反对 回复 2023-03-24
  • 1 回答
  • 0 关注
  • 148 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信