我创建了像这样的下拉组件
const CONTACTS_LIST = () => (
<select>
{
list_data &&
list_data .map((h, i) =>
(
<option key={i} value={h.list_id}>{h.name}</option>))
}
</select>
);
是否可以像这样使用 json 响应渲染 html?我可以使用 setstate 在常量中设置响应。但只是想知道这也可能吗?
const CONTACTS_LIST = () => (
fetch(URL)
.then(response => response.json())
.then(json => {
(
render '
( <select>
{
json &&
json.map((h, i) =>
(
<option key={i} value={h.list_id}>{h.name}</option>))
}
</select>
)
)
);
请推荐
最佳答案
建议在componentDidMount方法内进行异步请求,用从api获取的数据更新组件的状态,更新状态时组件会重新渲染并验证是否有元素,如果有则 的选项。 希望对您有帮助。
class MyComponent{
constructor () {
super();
this.state = {
list_data: []
};
}
componentDidMount () {
const URL = "";
fetch(URL).then(response => response.json())
.then(json => {
this.setState({
list_data: json
});
});
}
render () {
return (
<select>
{
list_data.length === 0
? <option value="">Waiting moment</option>
: list_data.map(({ h, i }) => (
<option key={i} value={h.list_id}>{h.name}</option>
))
}
</select>
)
}
}
如果你使用的是 React 16,你可以使用 Hooks、useState 和 useEffect,试试这种方法
import React, { useEffect, useState } from 'react';
function myComponent () {
const [list_data, set_list_data] = useState([]);
useEffect(() => {
const URL = "";
fetch(URL).then(response => response.json())
.then(json => {
set_list_data(json);
});
}, []);
return (
<select>
{
list_data.length === 0
? <option value="">Waiting moment</option>
: list_data.map(({ h, i }) => (
<option key={i} value={h.list_id}>{h.name}</option>
))
}
</select>
);
}
关于javascript - React js 使用 json 响应渲染功能性 html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58775600/