对于像您这样的情况,React中的一个常见模式是首先获取您的异步数据,然后将其保存为状态,这反过来又会触发您的组件的重新渲染。
React 元素是 React 查找更改时使用的基本构建块,并在每次触发渲染阶段时创建(例如render,类组件中的方法)。作为其内部差异算法实现的一部分, React 可能会调用render多次,因此您最好不要在渲染阶段依赖异步操作——它需要一个同步的返回值。
您可以像这样为类组件实现它:
class ExampleComp extends React.Component {
state = { nameBaseUrlTuples: [] };
componentDidMount() {
this.getLinkName("cars/honda");
}
render() {
return this.state.nameBaseUrlTuples.map((nameBaseUrlTuple, index) => (
<Link to={"/" + nameBaseUrlTuple[1]} key={index}>
{nameBaseUrlTuple[0]}
</Link>
));
}
async getLinkName(segments) {
const arr = segments.split("/"); // cars/honda
let baseUrl = arr[0];
const nameBaseUrlTuples = await Promise.all(
// not sure, if you also want to iterate over first index
// seems as first is your root path segment containing sub categories
arr.map(async (item, index) => {
let name = await getCategoryNameFromSlug(baseUrl);
// You could remove this side effect by
// using map callback's third "array" argument and
// compose your URL with array.slice(0, index+1).join("/") or similar
baseUrl = baseUrl + "/" + item;
return [name, baseUrl];
})
);
this.setState({ nameBaseUrlTuples });
}
}