我想将 axios 的 return 用于全局状态,但是 Promise { <pending> }

I want to use axios's return to global state ,but Promise { <pending> }

const Board = () => {

    ...

    const {selected} = useSelector(state => state.board);
    // In Redux reducer ->
    // const initialState = {
    // selected : {}
    // }

    const getOnePost = async (id) => {
        try {
          const response = await axios.get(`/api/v1/post/${id}`);
          const getOnePostData = await response.data;
          selected = getOnePostData //I want to use Redux to use global state...
          console.log(selected) //TypeError... and How to use global state..?
        } catch(error) {
          alert(error.response.data.message);
          return Promise.reject(error)
        }
      }

    const postClickHandler = (postId) =>
    {
        if(postId) {
            // dispatch(boardSelected(postId));
            getOnePost(postId)
        }
    }

    ...

}

此代码使用 axios.get 接收 post 信息。

我想使用 api 的 return 到全局状态(Redux 状态)。

    const getOnePost = async (id) => {
        try {
          const response = await axios.get(`/api/v1/post/${id}`);
          const getOnePostData = await response.data;
          return getOnePostData //return data
        } catch(error) {
          alert(error.response.data.message);
          return Promise.reject(error)
        }
      }

    const postClickHandler = (postId) =>
    {
        if(postId) {
            getOnePost(postId).then((response)=>{
                return{...selected, selected: response} //But Seleted: {}
            })
        }
    }

Axios 是一个 Promised-based JavaScript 库,用于发送 HTTP 请求, 你必须在 then 方法中得到承诺的结果。 试试这个

const Board = () => {
...

const {selected} = useSelector(state => state.board);
// In Redux reducer ->
// const initialState = {
// selected : {}
// }

const getOnePost = async (id) => {
    try {
      const response = await axios.get(`/api/v1/post/${id}`);
      response.then(function (rec) {
            selected = rec.data //
            //here update you state 
            console.log(selected)
        }).catch(function (error) {
            console.log(error);
        }); 
    } catch(error) {
      alert(error.response.data.message);
      return Promise.reject(error)
    }
  }

const postClickHandler = (postId) =>
{
    if(postId) {
        // dispatch(boardSelected(postId));
        getOnePost(postId)
    }
}

...

}

您可以使用 .then()

处理 promise

尝试像下面这样初始化选择:

const response = await axios.get(`/api/v1/post/${id}`).then( response => {
 selected = response
})

不知道是什么数据。因此,尝试记录响应数据并使用它。