我想知道从rest api显示数据的最佳方法是什么。
其实我做的是:
componentDidMount()
调用fetch函数;setState
存储我的回复render()
时检查三元组它看起来像这样:
(getcall()
是一个获取函数):
async componentDidMount() {
const response= await getCall(
`event?ref=23876186`, // this is just to illustrate
);
this.setState({ payload: response})
}
然后在render()
我做了一些:
{this.state.payload ? (
<h1>{this.state.payload.event.name}</h1>) : ( <h1></h1>)}
我虽然从fetch
调用我的constructor
函数,但是在async
中调用constructor
函数很奇怪,你放弃了aync
的目的。
我想象一些像input
的情况:
<Input
type="text"
name="name"
id="name"
**value={this.state.event.name}**
placeholder="Name..."
onChange={this.handleName}
required
/>
如果我想为它设置一个值,比如this.state.event.name
,如果我有10个字段,那么我将有10 * 2倍这种代码,因为对于每一个我写了一个三元组。
那么从api调用显示数据的最佳方法是什么?
谢谢你的回答
如果没有设置payload
,你可以在null
方法的早期返回render
,而不是添加很多三元组。
例
class App extends React.Component {
state = {
payload: null
};
async componentDidMount() {
const response = await getCall("/event?ref=23876186");
this.setState({ payload: response });
}
render() {
const { payload } = this.state;
if (payload === null) {
return null;
}
return <div>{/* ... */}</div>;
}
}