我将material-ui与React function组件一起使用,并使用其Autocomplete组件。我自定义了它,每当我更改输入字段中的文本时,我都希望该组件呈现新的搜索结果。
callAPI("xyz")我在动作中调用API,并使用xyz参数,从这个函数组件调用调度方法。
这里的问题是,当组件进行调用时,它应该等待API响应,然后呈现结果,但它得到了一个未解决的承诺,因此它呈现失败。
<Paper square>
{callAPI("xyz").results.map(
result => console.log(result);
)}
</Paper>由于结果是一个未解决的承诺,它将无法映射。我需要一些方法来仅在数据可用时调用地图,或者在数据存在之前显示一些文本,然后在获取数据后更改。
任何更正此代码的建议都将非常有帮助。
编辑:
function IntegrationDownshift() {
return (
<div>
<Downshift id="downshift-simple">
{({
getInputProps,
getItemProps,
getMenuProps,
highlightedIndex,
inputValue,
isOpen,
selectedItem
}) => (
<div>
{renderInput({
fullWidth: true,
InputProps: getInputProps({
placeholder: "Search users with id"
})
})}
<div {...getMenuProps()}>
{isOpen ?
<Paper square>
{callAPI(inputValue).users.map(
(suggestion, index) =>
renderSuggestion({
suggestion,
index,
itemProps: getItemProps({
item:
suggestion.userName
}),
highlightedIndex,
selectedItem
})
)}
</Paper>
: null}
</div>
</div>
)}
</Downshift>
</div>
);
}发布于 2019-06-03 02:49:09
React 16.8引入了Hooks
React钩子是允许您从功能组件“钩入”
状态和生命周期特性的函数。
所以你有了useState(),你可以用一个空数组声明一个状态变量,并在useEffect()中调用你的API,当你从API得到响应时填充状态:
function App() {
const [data, setData] = useState([]);
useEffect(() => {
callAPI("xyz").then(result => {
setData(result);
})
}, []);
if(!data.length) return (<span>loading...</span>);
return (
<Paper square>
{data.map(
result => console.log(result);
)}
</Paper>
);
}更多关于钩子的信息:https://reactjs.org/docs/hooks-intro.html。
发布于 2019-06-03 02:16:20
处理此问题的最简单方法是使用ternanry表达式,其最佳实践是在生命周期方法中调用API请求,然后将结果保存在本地状态中。
componentDidMount() {
callAPI("xyz").results.map(
result => this.setState(result);
}
<Paper square>
{this.state.results ?
this.state.results.map(
result => console.log(result);
: <p> Loading... </p>
)}
</Paper>https://stackoverflow.com/questions/56417661
复制相似问题