Redux thunk 不在数组上显示数据
Posted
技术标签:
【中文标题】Redux thunk 不在数组上显示数据【英文标题】:Redux thunk doesn't display data on array 【发布时间】:2021-12-14 19:28:14 【问题描述】:我正在使用 react 和 redux-thunk 制作 redux 电影。 我还是 Redux 的新手。我知道 Redux thunk 是一个中间件,用于处理 API 调用的异步函数。我的目标是在组件中显示 api 数据。我不知道丢失的点。 这是我的代码: action.js
import API from "../api/index";
import axios from "axios";
export const MovieSuccess = (data) => (
type: MOVIE_SUCCESS,
payload: data,
);
export const MovieError = (data) => (
type: MOVIE_ERROR,
payload: data,
);
export const MovieStart = () => (
type: MOVIE_START,
);
export const getMovies = () => (dispatch) =>
dispatch(MovieStart());
return axios
.get(API)
.then(( data ) =>
dispatch(MovieSuccess(data));
)
.catch((err) =>
dispatch(MovieError(err));
);
;
reducer.js
const initialState =
movies: [],
loading: false,
error: null,
;
export const MovieReducer = (state = initialState, action) =>
switch (action.type)
case MOVIE_START:
return
...state,
loading: true,
;
case MOVIE_SUCCESS:
return
...state,
movies: action.payload,
loading: true,
error: "",
;
case MOVIE_ERROR:
return
...state,
loading: false,
error: action.payload,
;
default:
return
...state,
;
;
export default MovieReducer;
对于商店,我输入了 index.js
import ReactDOM from "react-dom";
import "./index.css";
import "antd/dist/antd.css";
import App from "./App";
import MovieReducer from "./redux/reducer";
import Provider from "react-redux";
import createStore, applyMiddleware from "redux";
import thunk from "redux-thunk";
const store = createStore(MovieReducer, applyMiddleware(thunk));
ReactDOM.render(
<React.StrictMode>
<Provider store=store>
<App />
</Provider>
</React.StrictMode>,
document.getElementById("root")
);
App.js
import MainPage from "./Components/MainPage";
const App = () =>
return (
<>
<MainPage />
</>
);
;
export default App;
MainPage.js
import MovieCard from "../MovieCard";
import SearchInput from "../SearchInput";
import Layout from "antd";
import connect from "react-redux";
import getMovies from "../../redux/action";
const Header, Content = Layout;
const MainPage = (props) =>
useEffect(() =>
props.listMovies();
, []);
return (
<>
<div>
props.movies.map((key, data) => (
<div>
<p>key.id</p>
<p>data.title</p>
</div>
))
</div>
<Layout>
<Header>
<SearchInput />
</Header>
<Content>
<MovieCard />
</Content>
</Layout>
</>
);
;
const mapStateToProps = (state) => (
movies: state.movies,
);
const mapDispatchToProps = (dispatch) => (
listMovies: (data) => dispatch(getMovies(data)),
);
export default connect(mapStateToProps, mapDispatchToProps)(MainPage);
【问题讨论】:
【参考方案1】:您是否遇到任何错误?如果您是,请用更多解释更新您的问题,同时这可能是导致问题的原因:
props.movies.map((key, data) => (
<div>
<p>key.id</p>
<p>data.title</p>
</div>
))
试试改成
props.movies.map((data, index) => (
<div key=index>
<p>data.id</p>
<p>data.title</p>
</div>
))
如果不是这种情况,请提供更多信息,说明您面临的问题的性质。
【讨论】:
以上是关于Redux thunk 不在数组上显示数据的主要内容,如果未能解决你的问题,请参考以下文章
redux thunk - 承诺完成后如何在嵌套数组中调度数据
使用 Redux Thunk 时正确理解 useEffect 中的依赖数组