Javascript 使用json响应对js呈现函数式html进行响应
我创建了下拉组件,如Javascript 使用json响应对js呈现函数式html进行响应,javascript,reactjs,components,Javascript,Reactjs,Components,我创建了下拉组件,如 const CONTACTS_LIST = () => ( <select> { list_data && list_data .map((h, i) => ( <option key={i} value={h.list_id}>{h.name}</option>)) } </select> ); const CONTA
const CONTACTS_LIST = () => (
<select>
{
list_data &&
list_data .map((h, i) =>
(
<option key={i} value={h.list_id}>{h.name}</option>))
}
</select>
);
const CONTACTS\u LIST=()=>(
{
列出数据&&
列表数据映射((h,i)=>
(
{h.name})
}
);
可以像这样用json响应呈现html吗?。我可以使用setstate在常量中设置response。但我只是想知道这也有可能吗
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>
)
)
);
const CONTACTS\u LIST=()=>(
获取(URL)
.then(response=>response.json())
。然后(json=>{
(
渲染'
(
{
json&&
json.map((h,i)=>
(
{h.name})
}
)
)
);
请建议建议在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>
)
}
}
类MyComponent{
构造函数(){
超级();
此.state={
列表数据:[]
};
}
组件安装(){
const URL=“”;
fetch(URL).then(response=>response.json())
。然后(json=>{
这是我的国家({
列表数据:json
});
});
}
渲染(){
返回(
{
list_data.length==0
?等待时刻
:list_data.map({h,i})=>(
{h.name}
))
}
)
}
}
如果您使用的是react 16,那么可以使用钩子、useState和useffect,这样试试
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>
);
}
import React,{useffect,useState}来自“React”;
函数myComponent(){
const[list_data,set_list_data]=useState([]);
useffect(()=>{
const URL=“”;
fetch(URL).then(response=>response.json())
。然后(json=>{
设置列表数据(json);
});
}, []);
返回(
{
list_data.length==0
?等待时刻
:list_data.map({h,i})=>(
{h.name}
))
}
);
}
您可以将json响应作为道具传递给要呈现的组件
fetch(URL)
.then(response => response.json())
.then(
<Component data={response} />
)
fetch(URL)
.then(response=>response.json())
.那么(
)
在
then
块中使用html代码有点违背React的目的。请格式化您的代码并明确您的问题;这将帮助我们理解您的问题和您尝试过的内容。您的第二个代码段没有有效语法,第三个代码段不完整。我想问的是,可以呈现html组件吗使用json Response?您需要具有cycle的组件,以便获得异步数据,生命周期是通过继承组件类获得的。根据React版本的不同,您可以使用用于创建具有异步数据的组件函数的挂钩。您使用的React版本是@NeerajVerma。@JorgeMartinezJimenez存在语法错误:['']
应该是[]
。您没有传递任何依赖项。在设置状态之前,您还应该检查组件是否仍然[mounted[()。