Reactjs 为什么我的动作没有在减速器中触发?
有人知道为什么点击按钮时什么都没发生吗 当点击按钮时,我试图从服务器上获取movielist,但它甚至没有显示动作正在按我预期的方式进行 我的反应指数jsReactjs 为什么我的动作没有在减速器中触发?,reactjs,redux,Reactjs,Redux,有人知道为什么点击按钮时什么都没发生吗 当点击按钮时,我试图从服务器上获取movielist,但它甚至没有显示动作正在按我预期的方式进行 我的反应指数js import React from 'react'; import { connect } from 'react-redux'; import { getMovies } from '../../actions/movieActions'; const Home = ({ movie }) => { const handleCl
import React from 'react';
import { connect } from 'react-redux';
import { getMovies } from '../../actions/movieActions';
const Home = ({ movie }) => {
const handleClick = () => {
getMovies();
};
return (
<div>
<button onClick={() => handleClick()}>Get Movies</button>
</div>
);
};
const mapStateToProps = state => ({
movie: state.movie.movies
});
export default connect(mapStateToProps, { getMovies })(Home);
我的电影减速器
import { GET_MOVIES } from '../actions/types';
const initialState = {
movies: null
};
export default (state = initialState, action) => {
switch (action.type) {
case GET_MOVIES:
return {
...state,
movies: action.payload
};
default:
return state;
}
};
我的电影动作
import { GET_MOVIES } from './types';
// get movies from server
export const getMovies = () => async dispatch => {
try {
const res = await fetch('http://localhost:5000/api/movies');
const data = await res.json();
dispatch({
type: GET_MOVIES,
payload: data
});
} catch (error) {
console.log(error);
}
};
my types.js
export const GET_MOVIES = 'GET_MOVIES';
my store.js
import { createStore, applyMiddleware } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension';
import thunk from 'redux-thunk';
import rootReducer from './reducers';
const initialState = {};
const middleware = [thunk];
const store = createStore(
rootReducer,
initialState,
composeWithDevTools(applyMiddleware(...middleware))
);
export default store;
您的错误是直接调用操作,而不是此处的
connect
edgetMovies
prop:
const handleClick = () => {
getMovies();
};
应该是:
const handleClick = () => {
this.props.getMovies();
};
将
export-const-getMovies=()=>async dispatch=>{
更改为export-const-getMovies=async dispatch=>{
@technophyle不工作,redux-thunk允许您在函数中返回函数。这与编写export-const-getMovies=()=>{return async(dispatch)=>{…}啊,你说得对。我补充了答案。
const handleClick = () => {
this.props.getMovies();
};