Reactjs ×;对象作为React子对象无效(找到:键为{author,quote}的对象)。如果要呈现子对象集合,请使用数组
我正试图像这样将一个对象传递到React组件中,但收到上述错误:Reactjs ×;对象作为React子对象无效(找到:键为{author,quote}的对象)。如果要呈现子对象集合,请使用数组,reactjs,object,error-handling,components,Reactjs,Object,Error Handling,Components,我正试图像这样将一个对象传递到React组件中,但收到上述错误: class RandomQuoteBox extends React.Component{ render(){ return( <div class="container"> <Quote /> <div class="row"> <div class="col">
class RandomQuoteBox extends React.Component{
render(){
return(
<div class="container">
<Quote />
<div class="row">
<div class="col">
</div>
<div class="col-8">
<div class="card" style={{
backgroundColor: '#FFDC00',
width: '500px',
height: '300px',
margin: '0 auto'
}}>
<div>
<Author {...QUOTES}/>
</div>
<div>
<Button />
</div>
</div>
</div>
<div class="col">
</div>
</div>
</div>
);
}
}
下面是作者函数:
const Author = (props) => {
return <p>{props.quotes}</p>
}
const Author=(道具)=>{
返回{props.quotes}
}
当我将数组直接传递到RandomQuote组件中时,它会正确显示。然而,我希望有一个外部对象,它同时包含两个键,author和quote。然后分别呈现Author和Quote组件。(我没有在这里列出Quote组件,因为一旦我找到了一个,我就应该能够找到它)。我认为您希望做的是:
<div>
{ QUOTES.map(quote => <Author quote={quote} /> )}
</div>
const Author = quote => {
return <p>{quote.author} says {quote.quote}<p>
}
{QUOTES.map(quote=>)}
const Author=quote=>{
return{quote.author}表示{quote.quote}
}
QUOTES
是一个数组,因此为了渲染它,您需要使用map()
下面的解决方案
function AuthorPrint({authors}) {
return authors.map(author => (
<p>{author.name}</p>
))
}
<div>
<AuthorPrint authors={QUOTES}/>
</div>
const QUOTES = [
{name: 'test 1', quote: 'tester 1'},
{name: 'test 2', quote: 'tester 2'},
{name: 'test 3', quote: 'tester 3'},
{name: 'test 4', quote: 'tester 4'},
{name: 'test 5', quote: 'tester 5'},
{name: 'test 6', quote: 'tester 6'},
];
函数AuthorPrint({authors}){
返回authors.map(author=>(
{author.name}
))
}
常量引号=[
{name:'test 1',引号:'tester 1'},
{名称:'test2',引号:'tester2'},
{名称:'test 3',引号:'tester 3'},
{名称:'test4',引号:'tester4'},
{名称:'test 5',引号:'tester 5'},
{名称:'test 6',引号:'tester 6'},
];
您的
组件现在看起来怎么样?
function AuthorPrint({authors}) {
return authors.map(author => (
<p>{author.name}</p>
))
}
<div>
<AuthorPrint authors={QUOTES}/>
</div>
const QUOTES = [
{name: 'test 1', quote: 'tester 1'},
{name: 'test 2', quote: 'tester 2'},
{name: 'test 3', quote: 'tester 3'},
{name: 'test 4', quote: 'tester 4'},
{name: 'test 5', quote: 'tester 5'},
{name: 'test 6', quote: 'tester 6'},
];