我是新手做出反应。
this.state = { histories: [
{
"qas":[
{"question": "hi1", "answer": "hello1"},
{"question": "hi2", "answer": "hello2"}
]
}
] };
render(){
return (
<div>
<History
histories={this.state.histories} />
</div>
);
}
在单独的组件页面中,我想使用react js通过循环或地图渲染问题和答案,但是我尝试了地图,它没有识别地图。我试过循环,但它没有得到它的子属性。
const history = ({histories}) => {
return(
<div>
{histories[0].qas[0].question}
</div>
<div}>
{histories[0].qas[0].answer}
</div>
);
}
答案 0 :(得分:1)
它不承认这个历史,因为我打赌它们在你的开始时是不确定的。
root /path/to/root;
index index.php;
location / {
try_files $uri $uri/ @rewrite;
}
location @rewrite {
return 301 /category$request_uri;
}
location ~ \.php$ {
try_files $uri =404;
...
}
location ~ ^/(category|tags|feeds) {
try_files $uri $uri/ /index.php;
}
另一个问题可能是const history = ({histories}) => {
if (!histories || histories.length < 1) return (<div>nothing</div>);
return histories.map(v => (<div>JSON.stringify(v)</div>))
}
。在您的示例中未定义。
答案 1 :(得分:1)
以下是地图的示例,希望它会有所帮助。
const History = ({histories}) => {
// Quick, hacky way to set key.
// More on keys in React https://facebook.github.io/react/docs/lists-and-keys.html#keys
let key = 1;
const questionsAndAnswers = histories[0].qas.map(child =>
<div key={key++}>
<div>{child.question}</div>
<div>{child.answer}</div>
</div>
);
return (
<div>{questionsAndAnswers}</div>
);
};
class Histories extends React.Component {
constructor(props) {
super(props);
this.state = {
histories: [
{
"qas":[
{"question": "hi1", "answer": "hello1"},
{"question": "hi2", "answer": "hello2"}
]
}
]
};
}
render() {
return(
<div>
<History histories={this.state.histories}/>
</div>
)
}
}
ReactDOM.render(
<Histories/>,
document.getElementById("history")
);
<div id="history"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
如果从<div>{questionsAndAnswers}</div>
中删除“div”,那么您将收到遇到的错误“有效的React元素(或null)......”。如果要渲染多个元素,则需要将它们包装在div中。有关此https://facebook.github.io/react/docs/jsx-in-depth.html#jsx-children