React.js中TypeError: Cannot read property 'push' of null错误排查求助(附TransationList.js代码)
Let's break down why you're hitting this error and fix it right away.
What's Causing the Error?
You're seeing this error because the list variable you're trying to call push() on is null. Here are the two key issues in your code:
Typos in localStorage key names
Look closely at yourreturnListmethod: you usetransations(missing the letter 'c') when reading from localStorage, but when setting the initial empty array, you use the correct keytransactions. Even after you set the empty array, you’re still trying to read from the wrong key—this returnsnull, makinglistnull when you try to push to it.Unnecessary array wrapping
In youronAddorEditmethod, you saveJSON.stringify([list])to localStorage. Sincelistis already an array, wrapping it in another[]creates a nested array (like[[...]]), which will break data handling later.
How to Fix It
Let's go through the fixes step by step:
1. Fix the localStorage Key Typo
Update both instances of transations in the returnList method to transactions—keep the key name consistent everywhere you interact with localStorage.
2. Fix the Array Storage Issue
Change JSON.stringify([list]) to JSON.stringify(list) when saving to localStorage. This stores the array directly instead of nesting it.
3. (Optional) Make returnList More Robust
Add error handling for JSON parsing (in case localStorage has invalid data) and simplify the logic to avoid redundant reads:
returnList() { const storedTransactions = localStorage.getItem('transactions'); // Initialize empty array if no data exists if (!storedTransactions) { const emptyList = []; localStorage.setItem('transactions', JSON.stringify(emptyList)); return emptyList; } // Safely parse stored data, fallback to empty array on failure try { return JSON.parse(storedTransactions) || []; } catch (e) { console.error('Error parsing transactions from localStorage:', e); return []; } }
Full Corrected Code
Here's your complete fixed component:
import React from 'react'; import TransationForm from './transactionsForm'; class TransationList extends React.Component { state = { list: this.returnList() } returnList() { const storedTransactions = localStorage.getItem('transactions'); if (!storedTransactions) { const emptyList = []; localStorage.setItem('transactions', JSON.stringify(emptyList)); return emptyList; } try { return JSON.parse(storedTransactions) || []; } catch (e) { console.error('Failed to parse transactions', e); return []; } } onAddorEdit = (data) => { const list = this.returnList(); list.push(data); localStorage.setItem('transactions', JSON.stringify(list)); this.setState({ list }); } render() { return ( <div className="container"> <TransationForm onAddorEdit={this.onAddorEdit} /> </div> ); } } export default TransationList;
内容的提问来源于stack exchange,提问作者srinivas senapathi

