亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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條經驗 獲得超16個贊

這是因為您的 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 關注
  • 186 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號