我有以下操作,发出异步 GET 请求:
export const getPolls = () => {
return async dispatch => {
try {
const polls = await serv.call('get', 'poll');
dispatch(setPolls(polls));
dispatch(removeError());
} catch (err) {
const error = err.response.data;
dispatch(addError(error.message));
}
}
}
然后,在组件 Polls 中,我希望能够调用此操作,以便我可以显示 Polls 列表。为此,我将其传递给该组件的 props:
export default connect(store => ({
polls: store.polls
}), {
getPolls
})
(Polls);
并通过 const {getPolls} = props;
我正在使用 React Hooks 创建和更改 Polls 组件状态。像这样:
const Polls = (props) => {
const {getPolls} = props
const [polls, setPolls] = useState([])
useEffect(() => {
const result = getPolls()
console.log(result)
setPolls(result)
}, [])
const pollsList = polls.map(poll => (<li key={poll._id}>{poll.question}</li>))
return (
<div>
<ul className='poll-list'>{pollsList}</ul>
</div>
)
}
使用此代码,我无法获得民意调查。当我 console.log 调用 getPolls() 的结果时,我可以看到我正在获得一个 Promise。但是,由于 getPolls() 是一个异步函数,难道不应该避免这种情况吗?我相信这个问题与我使用 React Hooks 的方式有关,尤其是 useEffect,但我想不通。
谢谢。
答案 0 :(得分:0)
当我 console.log 调用 getPolls() 的结果时,我可以看到我正在获得一个 Promise。但是,既然 getPolls() 是一个异步函数,难道不应该避免这种情况吗?
您对 async
函数存在根本性的误解。 async
和 await
只是帮助您处理 Promise
的语法。 async
函数 always returns a Promise
。为了获得实际值,您必须从另一个 await
函数内部 async
值。
但是您的 getPolls()
函数不是返回投票的函数。它不返回任何东西。它获取民意调查并使用数据调用 dispatch
以将民意调查存储在您的 Redux 存储中。
您需要在组件中执行的所有操作是调用 getPolls
以便执行此代码。您的 connect
HOC 正在从 polls
订阅 store.polls
的当前值,当 polls
函数更新 getPolls
时,store.polls
道具将自动更新(它通过调用 dispatch(setPolls(polls))
来实现)。
您的组件可以简化为:
const Polls = (props) => {
const {polls, getPolls} = props;
// effect calls the function one time when mounted
useEffect(() => {
getPolls();
}, [])
const pollsList = polls.map(poll => (<li key={poll._id}>{poll.question}</li>))
return (
<div>
<ul className='poll-list'>{pollsList}</ul>
</div>
)
}