📌  相关文章
📜  错误:对象作为 React 子项无效(找到:带有键 {counter} 的对象).如果您打算渲染一组子项,请改用数组. - 打字稿代码示例

📅  最后修改于: 2022-03-11 14:48:33.758000             🧑  作者: Mango

代码示例1
implemented a counter with increment, decrement and reset buttons and I was 
trying to display the count on to the screen but I was the above mentioned 
error.

In the code I had declared the count which is returned by useReducer hook as 
the object and I was directly trying to return it rather than the count 
property of it

I should actually return count.count and I was returning count only (object 
itself) not property.

We can stringify object and return the string also.

import React, { useReducer } from "react";

const initialState = {
count:0,
}
const reducer = (state, action) => {
    switch (action.type) {
        case 'increment':
            return {count:state.count + 1}
        case 'decrement':
            return {count:state.count - 1}
        case 'reset':
            return initialState
        default:
            return state
    }
}

function CounterWithReducer(props) {
  const [count, dispatch] = useReducer(reducer, initialState);

  return (
    <>
      

{count}

); } export default CounterWithReducer; In the above code {count} This section (in the return part ) is where I did the mistake instead of count I need to use count.count Summary is that if you trying to show object on to screen you can't either use JSON.stringify() or try to display any property of the object.