javascript - React js 使用 json 响应渲染功能性 html
问题描述
我创建了下拉组件,例如
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>
);
}