React redux未从API获取数据



嗨,我是redux的新手,我正在尝试使用www.themoviedb.org上的API创建一个电影应用程序。我正在尝试显示流行的电影,我确信API链接在poster中测试后有效,但我似乎不明白为什么redux没有获取数据。

//action
import { FETCH_POPULAR } from "./types";
import axios from "axios";
export const fetchPopularMovies = () => (dispatch) => {
axios
.get(
`https://api.themoviedb.org/3/movie/popular?api_key=${API}&language=en-US`
)
.then((response) =>
dispatch({
type: FETCH_POPULAR,
payload: response.data
})
)
.catch((err) => console.log(err));
};

//reducer
import { FETCH_POPULAR } from "../actions/types";
const initialState = {
popular: [],
};
export default function (state = initialState, action) {
switch (action.type) {
case FETCH_POPULAR:
return {
...state,
popular: action.payload,
};
default:
return state;
}
}

import React from "react";
import { connect } from "react-redux";
import Popular from "./Popular";

const FetchedPopular = (props) => {
const { popular } = props;
let content = "";
content =
popular.length > 0
? popular.map((item, index) => (
<Popular key={index} popular={item} />

))
: null;
return <div className="fetched-movies">{content}</div>;
};
const mapStateToProps = (state) => ({
popular: state.popular.popular,
});
export default connect(mapStateToProps)(FetchedPopular);

import React from "react";
import "../Styles.css";
const Popular = (props) => {
return (
<div className="movie-container">
<img
className="poster"
src={`https://image.tmdb.org/t/p/w400/${props.poster_path}`}
/>

</div>
);
};
export default Popular;

我真的说不出我错过了什么,有人能帮我吗?

需要在mapStateToProps旁边创建mapDispatchToProps。之后,您将能够从React组件调用您的Redux操作。我建议您将mapDispatchToProps作为Object表单。然后您需要使用此mapDispatchToProps作为connect方法的第二个参数。

当您将操作映射到组件时,您需要在某个地方调用它。例如,建议在组件安装上执行此操作。由于您的React组件是功能组件,因此您需要在ReactuseEffect挂钩中进行操作。

import React, { useEffect } from "react";
import { connect } from "react-redux";
import Popular from "./Popular";
import { fetchPopularMovies } from 'path_to_your_actions_file'
const FetchedPopular = (props) => {
const { popular } = props;
let content = "";
useEffect(()=> {
// call your mapped action (here it is called once on component mount due the empty dependency array of useEffect hook)
props.fetchPopularMovies();
}, [])
content =
popular.length > 0
? popular.map((item, index) => (
<Popular key={index} popular={item} />

))
: null;
return <div className="fetched-movies">{content}</div>;
};
const mapStateToProps = (state) => ({
popular: state.popular.popular,
});
// create mapDispatchToProps
const mapDispatchToProps = {
fetchPopularMovies
}
// use mapDispatchToProps as the second parameter of your `connect` method.
export default connect(mapStateToProps, mapDispatchToProps)(FetchedPopular);

此外,正如我在上面的评论中所写的,您的Popular没有道具poster_path,但它有道具popular,它可能具有属性poster_path

import React from "react";
import "../Styles.css";
const Popular = (props) => {
return (
<div className="movie-container">
<img
className="poster"
src={`https://image.tmdb.org/t/p/w400/${props.popular.poster_path}`}
/>

</div>
);
};
export default Popular;

最新更新