You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React报错TypeError:无法将null转为对象,寻求解决方案

Fixing "TypeError: can't convert null to object" in Your Burger Component

Hey there! Let's break down why you're hitting this error and how to fix it step by step.

What's Causing the Error?

The error TypeError: can't convert null to object is happening because you're calling Object.keys() on a null value. Looking at your code, that means props.ingredients is null when the component renders. Object.keys() only works on valid objects, so passing null here throws the error.

Quick Fixes to Apply

1. Add Default Props for Ingredients

Make sure your component has a fallback empty object for ingredients if it's not passed from the parent. You can do this in two simple ways:

Option A: Destructure with Default Value
Update the component parameter to set a default empty object right away:

const burger = ( { ingredients = {} } ) => {
  // Rest of your code stays exactly the same
}

Option B: Use defaultProps
Add this snippet at the bottom of your file, just before exporting the component:

burger.defaultProps = {
  ingredients: {}
};

export default burger;

2. Fix Parent Component Initial State

If the parent component passes ingredients from its state, double-check that the initial state isn't set to null. For example:

// ❌ Bad: initial state is null
const [ingredients, setIngredients] = useState(null);

// ✅ Good: initial state is an empty object
const [ingredients, setIngredients] = useState({});

3. Handle Database Defaults Correctly

Since you mentioned database default values, if your database returns null for the ingredients field when there's no data, convert that to an empty object when fetching the data. Here's an example of how to do that in your API request handler:

const fetchIngredients = async () => {
  const response = await fetch('/your-api-endpoint');
  const data = await response.json();
  // Convert null to empty object to avoid errors
  const ingredients = data.ingredients || {};
  setIngredients(ingredients);
};

4. Add a Safety Check Before Processing

For extra robustness, wrap the Object.keys() logic in a check to ensure props.ingredients is a valid object:

let transformedIngredients = [];

// Only process if ingredients exists and is an object
if (props.ingredients && typeof props.ingredients === 'object') {
  transformedIngredients = Object.keys(props.ingredients)
    .map(igKey => {
      return [...Array(props.ingredients[igKey])].map((_, i) => {
        return <BurgerIngredient key={igKey + i} type={igKey} />;
      });
    })
    .reduce((arr, el) => arr.concat(el), []);
}

if (transformedIngredients.length === 0) {
  transformedIngredients = <p>Please start adding ingredients!</p>;
}

Any of these fixes should prevent the error by ensuring Object.keys() always receives a valid object instead of null.

内容的提问来源于stack exchange,提问作者user10728848

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 11:27:39