简体   繁体   English

React useState hook - 对象作为 React 子对象无效

[英]React useState hook - Objects are not valid as a React child

I code useState like this post我像这篇文章一样编码 useState

 const [searchQuery, setSearchQuery] = React.useState({ Search1: "", Search2: "", });

And it throws它抛出

Objects are not valid as a React child (found: object with keys {Search1, Search2}).对象作为 React 子对象无效(找到:带有键 {Search1, Search2} 的对象)。 If you meant to render a collection of children, use an array instead.如果您打算渲染一组子项,请改用数组。

Full code完整代码

 import * as React from 'react' const Search = ({ handlerProp, searchQueryProp, inputName }) => { return ( <div className="App"> <input type="text" name={inputName} onChange={handlerProp} value={searchQueryProp} /> </div> ); } function App() { const [searchQuery, setSearchQuery] = React.useState({ Search1: "", Search2: "", }); function handleEmit({ target: { name, value } }) { setSearchQuery((prevState) => ({...prevState, [name]: value})); } return ( <div className="App"> <Search handlerProp={handleEmit} searchQueryProp={searchQuery} inputName="Search1" /> <Search handlerProp={handleEmit} searchQueryProp={searchQuery} inputName="Search2" /> </div> ); }

As I mentioned in the comments before adding the related codes, the problem is with your searchQuery object.正如我在添加相关代码之前的评论中提到的,问题出在您的searchQuery对象上。

Why did you get this error?你为什么会收到这个错误?

you passed an object instead of a string to the Search component.您向Search组件传递了一个对象而不是字符串 The input element, get a value property which is a string . input元素,获取一个value属性,它是一个string

The solution:解决方案:

So, change your App return section to pass a valid string for the searchQueryProp :因此,更改您的App返回部分以传递searchQueryProp的有效string

return (
    <div className="App">
      <Search handlerProp={handleEmit} searchQueryProp={searchQuery.search1} inputName="Search1" />
      <Search handlerProp={handleEmit} searchQueryProp={searchQuery.search2} inputName="Search2" />
    </div>
);

Note: always use the lowercase characters to define your variables and constant and only use the uppercase characters in the components name.注意:始终使用小写字符来定义变量和常量,并且仅在组件名称中使用大写字符。 you defined your state's value with Search1 and Search2 which is not correct.你定义你的状态与价值Search1以及Search2这是不正确的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM