React是非常状态的,并且由props驱动-将props传递给一个组件或由一个内部维护状态.在您的示例中,在不了解更多细节的情况下,似乎您唯一的选择是利用component state.这意味着您不能使用无状态组件,至少您要查看PureComponent或Component,即
import React,{ PureComponent } from 'react';
class Related extends PureComponent {
state = {
artists: null,error: null
}
constructor(props) {
this.super();
this.url = `/artist/${props.artistId}/related`;
}
getRelatedArtists = async () => {
try {
const res = await fetch(this.url);
const json = await res.json();
this.setState({ artists: json.data,error: null });
} catch(e) {
console.error(e);
this.setState({ error: 'Unable to fetch artists' });
}
}
renderError() {
if (!this.state.error) return null;
return (
{this.state.error}
)
}
renderArtistList() {
if (!this.state.artists) return null;
return this.state.artists.map((x,i) => (
Name: ${x.name}
Fans: ${x.nb_fans}
));
}
render() {
return (
Related artists
get {this.renderError()}
{this.renderArtistList()}
);
}
}
如果您使用的是React 16.x,那么您也许应该考虑使用Hooks.这就是作为功能组件的外观
import React,{ useState,useCallback } from 'react';
function Related(props) {
// setup state
const [artists,setArtists] = useState(null);
const [error,setError] = useState(null);
// setup click handler
const getRelatedArtists = useCallback(async () => {
try {
// fetch data from API
const res = await fetch(`/artist/${props.artistId}/related`);
const json = await res.json();
// set state
setArtists(json.data);
setError(null);
} catch(e) {
console.error(e);
setError('Unable to fetch artists');
}
},[props.artistId]);
// setup render helper
function renderArtist(artist,key) {
return (
Name: ${artist.name}
Fans: ${artist.nb_fans}
);
}
// render component
return (
Related artists
get {error}
{artists && artists.map(renderArtist)}
)
}