错误:对象作为 React 子对象无效(找到:带有键 {} 的对象)

时间:2021-02-16 07:22:44

标签: reactjs typescript react-hooks tsx

我是第一次学习 ts 的初学者。预先感谢您分享您的知识。我正在制作待办事项清单。我曾经做出反应来完成它。但是现在我同时使用 react 和 typescript 来完成代码。 我有一个错误。我不知道是什么问题。请帮帮我。

Error: Objects are not valid as a React child (found: object with keys {}). If you meant to render a collection of children, use an array instead.

enter image description here

点击here查看完整代码

我认为问题出在这个文件上。

// contet.tsx

import React, { createContext, useReducer, useContext, Dispatch } from 'react';
import reducer from "./reducer";
import { Action } from './actions'

export interface ITodo {
  id: string;
  text: string;
};

export interface State {
  toDos: ITodo[];
  completed: ITodo[];
}

interface ContextValue {
  state: State;
  dispatch: Dispatch<Action>;
}
export const initialState = {
  toDos: [],
  completed: [],
};

const ToDosContext = createContext<ContextValue>({
  state: initialState,
  dispatch: () => { console.error("called dispatch outside of a ToDosContext Provider") }
});

export const ToDosProvider = ({ children }: { children: React.ReactNode }) => {
  const [state, dispatch] = useReducer(reducer, initialState);
  return (
    <ToDosContext.Provider value={{ state, dispatch }}>
      {children}
    </ToDosContext.Provider>
  );
};

export const useTodosState = (): State => {
  const { state } = useContext(ToDosContext);
  return state;
};

export const useTodosDispatch = (): Dispatch<Action> => {
  const { dispatch } = useContext(ToDosContext);
  return dispatch;
};

这是 App.tsx

import React from "react";
import Add from "./Add";
import Title from "./Title";
import Progress from "./Progress";
import List from "./List";
import ToDo from "./ToDo";
import styled from "styled-components";
import { useTodosState } from '../context';

const App = () => {
  const { toDos, completed } = useTodosState();
  console.log(toDos);
  return (
    <Title>
      <Add />
      <Progress />
      <Lists>
        <List title={toDos.length !== 0 ? "To Dos" : ""}>
          {toDos.map((toDo) => (
            <ToDo key={toDo.id} id={toDo.id} text={toDo.text} isCompleted={false} />
          ))}
        </List>
        <List title={completed.length !== 0 ? "Completed" : ""}>
          {completed.map((toDo) => (
            <ToDo key={toDo.id} id={toDo.id} text=
              {toDo.text} isCompleted />
          ))}
        </List>
      </Lists>
    </Title >
  )
}
export default App;

2 个答案:

答案 0 :(得分:2)

我查看了您分享的存储库,问题出在 List.tsx 组件以及您尝试从组件访问道具的方式。应该是

const List = ({ title, children }: any) => (

代替

const List = (title: any, children: any) => (

在 react 函数组件中,props 对象只接受一个参数。

此外,如果您想在那里添加类型,您可以执行 {title:string; children: ReactElement| ReactElement[]}

答案 1 :(得分:1)

我认为这是解决这种情况的更好方法。您可以使用 PropsWithChildren 您可以使用 check it out 了解详情。

举个例子

export interface SearchProps {
  height: number
}

function Search({ children }: PropsWithChildren<SearchProps>) {
..
..
return()
}