我可以在我遇到的问题上使用一些指导/推动/灯光。我试图找出一种方法来创建fetchUserImg,以便它可以显示用户个人资料图片。最初,用户的ID号来自事件的host_id号。所以基本上组件应该1)获取事件的信息(包括host_id)2)将host_id传递给fetchUserImg以获取用户的个人资料图片。但我遇到了一个我一直试图解决的问题。我做了大量的搜索,虽然我发现了类似的情况,但我无法复制解决方案来处理这个实例。我已经贴上了这个贴纸。
https://pastebin.com/7pdPG19c - EventsFeed.js
class EventsFeed extends Component {
constructor(props) {
super(props);
}
async componentWillMount() {
const eventId = this.props.match.params.id;
await this.props.fetchEventInfo(eventId);
/* fetching user's profile picture here */
const hostId = this.props.selectedEvent.info.user_id;
const userPhoto = await this.props.fetchUserImg(hostId);
/* done fetching user's profile picture */
await this.props.fetchUserInfo(sessionStorage.getItem('userId'));
}
onCreatePost() {
const body = this.props.eventWallPost;
const eventId = this.props.match.params.id;
const authorId = sessionStorage.getItem('userId');
this.props.createPostOnEventWall({ body, eventId, authorId}, this.props.fetchEventInfo);
}
https://pastebin.com/knKyrjdr - user_reducer.js
import { FETCH_USER_INFO, FETCH_USER_IMG } from '../actions/types';
const INITIAL_STATE = {}
export default (state = INITIAL_STATE, action) => {
switch(action.type) {
case FETCH_USER_INFO:
return action.payload.data;
case FETCH_USER_IMG:
return action.payload.data;
default:
return state;
}
};
https://pastebin.com/Enf2Pc6p - user_actions.js
export function fetchUserImg(userId) {
async (dispatch) => {
const response = await axios({
method: 'get',
url: 'http://localhost:9000/api/v1/users/info',
headers: {"id": userId}
});
return dispatch({
type: FETCH_USER_IMG,
payload: response.data.photo })
};
}
https://pastebin.com/jCCF7TrS - types.js
export const FETCH_USER_IMG = 'fetch_user_img';
加载页面时出错
Unhandled Rejection (Error): Actions must be plain objects. Use custom middleware for async actions.
4 stack frames were collapsed.
EventsFeed._callee$
src/EventsFeedPage/EventsFeed.js 31
28 |
29 | /* fetching user's profile picture here */
30 | const hostId = this.props.selectedEvent.info.user_id;
> 31 | const userPhoto = await this.props.fetchUserImg(hostId);
32 | /* done fetching user's profile picture */
33 |
34 | await this.props.fetchUserInfo(sessionStorage.getItem('userId'));
View compiled
5 stack frames were collapsed.
答案 0 :(得分:0)
正如错误所说,您应该使用处理异步操作的自定义中间件,因为默认情况下操作必须是普通对象。
例如,你可以尝试这个:https://npmjs.com/package/redux-async-action
但是如果你需要它只是因为axios redux-axios-middleware
(https://www.npmjs.com/package/redux-axios-middleware)也可以做这项工作。
答案 1 :(得分:0)
您的fetchUserImg
似乎没有返回任何内容。它必须返回一个接收dispatch作为参数的函数:
export function fetchUserImg(userId) {
return async (dispatch) => {
// ...
}
}