我正在用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);
你得到任何错误吗?如果你是,请更新你的问题与更多的解释,同时这可能是什么导致的问题:
{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>
))}
如果情况并非如此,请提供更多信息,说明您所面临的问题的性质。