Javascript React:无法呈现获取状态的映射
这就是我的问题: 我获取一个API,下面是操作:Javascript React:无法呈现获取状态的映射,javascript,reactjs,redux,Javascript,Reactjs,Redux,这就是我的问题: 我获取一个API,下面是操作: const OPTIONS = { method: 'GET', headers: { 'X-RapidAPI-Host': 'api-football-v1.p.rapidapi.com', 'X-RapidAPI-Key': '44316d2130msh21fed66e06e6a24p1dd597jsnf2e92ca6ac85' } }; export function setLeagues() { con
const OPTIONS = {
method: 'GET',
headers: {
'X-RapidAPI-Host': 'api-football-v1.p.rapidapi.com',
'X-RapidAPI-Key': '44316d2130msh21fed66e06e6a24p1dd597jsnf2e92ca6ac85'
}
};
export function setLeagues() {
const countries =
[
{
france: ["Ligue 1", "Ligue 2"]
},
{
england: ["Premier League"]
},
{
germany: ["Bundesliga 1"]
}
];
let leagues = [];
countries.forEach((country) => {
fetch(`https://api-football-v1.p.rapidapi.com/v2/leagues/current/${Object.keys(country)[0]}`, OPTIONS)
.then(response => response.json())
.then((data) => {
Object.values(country)[0].forEach((league) => {
data.api.leagues.filter((league_api) => {
if(league_api.name === league) {
leagues.push(league_api);
}
});
});
});
});
return {
type: 'SET_LEAGUES',
payload: leagues
};
}
联盟返回正确的联盟对象数组。
这是减速器:
export default function(state, action) {
if (state === undefined) {
return [];
}
if (action.type === 'SET_LEAGUES') {
return action.payload;
} else {
return state;
}
}
最后是我的容器:
class LeaguesLabel extends Component {
componentDidMount() {
this.props.setLeagues()
}
render() {
console.log(this.props.leagues);
return(
<div>
<ul>
{
this.props.leagues.map((league) => {
return(
<li>
{league.name}
</li>
);
})
}
</ul>
</div>
);
}
}
function mapDispatchToProps(dispatch) {
return bindActionCreators(
{ setLeagues: setLeagues },
dispatch
);
}
function mapStateToProps(state) {
return {
leagues: state.leagues
}
}
export default connect(mapStateToProps, mapDispatchToProps)(LeaguesLabel);
类联盟标签扩展组件{
componentDidMount(){
this.props.setLeagues()
}
render(){
console.log(this.props.leagues);
返回(
{
这个.props.leagues.map((league)=>{
返回(
-
{league.name}
);
})
}
);
}
}
功能图DispatchToprops(调度){
返回bindActionCreators(
{setLeagues:setLeagues},
派遣
);
}
函数MapStateTops(状态){
返回{
联盟:州。联盟
}
}
导出默认连接(mapStateToProps、mapDispatchToProps)(联盟标签);
我当然会把setLeague导入这个容器
当my console.log(this.props.leagues)显示包含“league”的对象的良好数组时,不会显示任何内容
提前感谢您的帮助 问题在于,您正在调用一个异步函数,并在其外围返回结果 在接收API调用的答案之前调用return语句会发生什么情况 因此,列表将为空 您应该在这里阅读异步函数 除此之外,为了在redux操作中使用异步函数,您应该使用redux thunk
这里有一个很好的例子->另一个答案是正确的,但要进一步扩展,请像这样思考您的函数 首先,它处理该块,然后遍历各个国家,并开始执行获取请求:
countries.forEach((country) => {
fetch(`https://api-football-v1.p.rapidapi.com/v2/leagues/current/${Object.keys(country)[0]}`, OPTIONS)
.then(response => response.json())
.then((data) => {
Object.values(country)[0].forEach((league) => {
data.api.leagues.filter((league_api) => {
if(league_api.name === league) {
leagues.push(league_api);
}
});
});
});
});
接下来,在前一个工作as有机会做任何事情之前,它将处理以下块:
return {
type: 'SET_LEAGUES',
payload: leagues
};
因此,它已开始运行您的countries.forEach
,但获取承诺在该函数之外解析,因此在将任何数据推入数组之前,您已经返回了它
尝试使用await/async
语法,这将使您更容易处理与承诺的争论,例如:
export async function setLeagues() {
const countries = [
{
name: "france",
leagues: ["Ligue 1", "Ligue 2"],
},
{
name: "england",
leagues: ["Premier League"],
},
{
name: "germany",
leagues: ["Bundesliga 1"],
},
]
let payload = []
for (const country of countries) {
const { name, leagues } = country
const response = await fetch(
`https://api-football-v1.p.rapidapi.com/v2/leagues/current/${name}`,
OPTIONS
)
const data = await response.json()
for (const apiLeague of data.api.leagues) {
if (leagues.includes(apiLeague.name)) {
payload.push(apiLeague)
}
}
}
return {
type: "SET_LEAGUES",
payload,
}
}
这回答了你的问题吗?谢谢你的回答,但我不明白。。我的异步函数是setLeague?如果是,为什么在API回答之前调用返回?首先,在redux操作中,您应该使用redux thunk中间件来处理异步函数。没有它,它就无法工作。其次,如果API启用,我将尝试在一次调用中调用所有联盟,或者创建一个子react组件,其中每个成员负责为其联盟调用API。我使用一个中间件:const middleware=applymidleware(reduxPromise,logger);store={createStore(reducers,{},middleware)}很好,您已经有了添加中间件的代码。Redux thunk是一个额外的中间件,可以在Redux操作中启用异步调用,我将用一个示例Hi更新我的答案!谢谢你的回答。我理解其中的道理。我通过分析测试了您的代码,但是当您在setLeagues()中返回之前将console.log“payload”记录在日志中时,它是空的…好的,这很有效!!!我只是在从“redux promise”导入promiseMiddleware时犯了一个错误。非常感谢你,我理解我的错误,你帮了我很多。非常感谢。