【发布时间】:2018-06-04 14:47:06
【问题描述】:
以下是我将数据返回到 Container 的 reducer 文件:
import FETCH_MEDIAID from '../actions/index';
export default function(state = [], action){
console.log('Action Received', action);
switch(action.type){
case FETCH_MEDIAID:
return action;
}
return state;
}
我的获取请求如下(一旦用户在输入字段中插入 Instagram 内容 url,我想返回有关 Instagram 内容的媒体元数据):
import axios from 'axios';
export const FETCH_MEDIAID = 'FETCH_MEDIAID';
const RootURL= `https://api.instagram.com/oembed?url=`;
export function fetchMediaID(shortcode){
const url = `${RootURL}${shortcode}`;
const request = axios.get(url);
console.log('Request is: ', request);
return {
type: FETCH_MEDIAID,
payload: request
};
}
我是处理 API 响应的新手。
输出组件:
import React, {Component} from 'react';
import {connect} from 'react-redux';
class Output extends React.Component {
renderMediaid(metaData){
return(
<tr>
<td>{metaData.media_id}</td>
</tr>
);
}
render(){
return(
<table className='table table-hover'>
<tbody>
{this.props.mediaid.map(this.renderMediaid)}
</tbody>
</table>
);
}
}
function mapStateToProps(state){
return {mediaid: state.mediaid};
}
export default connect(mapStateToProps)(Output);
【问题讨论】:
-
1) 您是在 AJAX 请求上使用 then 还是 async/await ? 2)你可能想看看 action.payload.data
-
嗨@greybarkans,1:那时我没有使用。我认为这是使用 axios 库的异步请求。 2:如果我使用 action.payload.data 在容器中使用该数据时会出现控制台错误
-
在您的函数 fetchMediaId 中创建动作类型和有效负载的代码在哪里?你是在你的减速器中返回 action.payload.data 还是只是'action'?您是否正在检查 action.payload.data 的对象是否与容器中的逻辑匹配?
-
在您的 reducer 中,您需要返回以不可变方式更新的状态,其中包含将发送到您连接的容器组件的所需数据。现在,您正在返回操作而不是 case 语句分支中的更新状态。此外,您可能需要在您的操作中使用某种中间件,以便仅在异步 HTTP 调用完成时分派操作。此外,您可能希望创建另一个表示成功响应的操作,例如请求操作和成功操作。这可以通过多种方式解决。
-
reactjs/redux async example 可以作为在 redux 中处理异步操作以及在 reducer 中不可变地更新状态的整体方法的一个很好的起点。