我使用API"https://www.definitions.net/definitions_api.php"制作一个反应.js应用程序。 当我记录 data.result 时,它会输出正确的结果数组,但是当我映射状态时,我收到此错误:"对象作为 React 子项无效(找到:带有键 {} 的对象(。如果要呈现子项的集合,请改用数组。
//states
const [definition, setDefinition] = useState([])
const [search, setSearch] = useState('')
const [query, setQuery] = useState('')
useEffect(() => {
getDef()
}, [query])
//FETCH
const getDef = async () => {
const response = await fetch(`....`)
const data = await response.json()
setDefinition(data.result);
//handle input
const updateSearch = e => {
setSearch(e.target.value)
}
//get the final query onSubmit
const getQuery = e =>{
e.preventDefault()
setQuery(search)
setSearch('')
}
return (
{ definition && definition.map(item => (
<Definition term={item.term}
partofspeech = {item.partofspeech}
definition={item.definition}
example = {item.example}
/>
)
)
}
);
在定义组件中,我解构了道具:
function Definition({term, partofspeech, definition, example}) {
return (
<div className="definition">
<h4>{term} ({partofspeech})</h4>
<p>{definition}</p>
<p>{example}</p>
</div>
)
}
欢迎任何帮助,谢谢。
试试这个,当你循环组件循环定义而不带根元素时,会导致错误
const Component = () => {
....
return (
<Fragment>
{ definition && definition.map(item => (
<Definition term={item.term}
partofspeech = {item.partofspeech}
definition={item.definition}
example = {item.example}
/>
)
)
}
)
</Fragment>
)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
作为回报,您同时拥有圆形和卷曲({})
您可以删除两者,您应该直接返回
return definition && definition.map(item => (
<Definition term={item.term}
partofspeech = {item.partofspeech}
definition={item.definition}
example = {item.example}
/>
));
简短的片段,您可以运行它并查看:
const { useState } = React;
const App = () => {
const [users,setUsers] = useState(['Vivek' , 'Darshita', 'Darshvi' , 'Coming..']);
return users.map(user => <p>{user}</p>);
}
ReactDOM.render(<App />, document.getElementById('react-root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react-root"></div>