我正试图从Django REST API中获取信息,但派遣动作reducer无法正常工作。我正在使用Material UI,Hooks,Redux。
Action Reducer代码:
import axios from 'axios';
import { GET_NOTE } from './types';
// GET NOTE
export const getNote = () => (dispatch) => {
console.log('Contacting API');
axios.get('/api/note/')
.then(response => {
console.log('api contact');
dispatch({
type: GET_NOTE,
payload: response.data
});
}).catch(error => console.log(error));
};
调用它的功能组件:
import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { getNote } from '../../redux/actions/note'
import { Typography } from '@material-ui/core';
import { makeStyles } from '@material-ui/core/styles';
const useStyles = makeStyles(theme => ({
container: {
minHeight: '100vh',
paddingTop: '25vh',
},
}))
const Note = () => {
const classes = useStyles();
console.log(getNote());
React.useEffect(() => {
console.log('componentDidMount is useEffect in React Hooks');
getNote();
}, [])
Note.propTypes = {
note: PropTypes.array.isRequired
}
return (
<div className={classes.container}>
<Typography>
This is note page.
</Typography>
</div>
);}
const mapStateToProps = state => ({
note: state.note.note
});
export default connect(
mapStateToProps,
{ getNote }
)(Note);
我跟踪了代码未运行的位置,它位于“注释”功能组件中的getNote()函数上。控制台就是这样:
note.jsx:21 dispatch => {
console.log('Contacting API');
axios__WEBPACK_IMPORTED_MODULE_0___default.a.get('/api/note/').then(response => {
console.log('api contact');
dispatch({
type: _types__W…
note.jsx:24 componentDidMount is useEffect in React Hooks
Github的代码链接:https://github.com/PranishShresth/E-classmate
答案 0 :(得分:1)
问题是您不会调用getNote
通过connect
为您传递的注入props
,而是调用导入的原始函数。
您可以在功能组件中使用connect
,但是react-redux
也可以为您提供useSelector
和useDispatch
hooks,它们可以代替connect
HOC < / p>
使用connect
const Note = props => {
useEffect(props.getNote, [])
return ...
}
// don't define propTypes inside the component body
Note.propTypes = {
note: PropTypes.array.isRequired
}
const mapStateToProps = state => ({
note: state.note.note
})
export default connect(
mapStateToProps,
{ getNote }
)(Note)
使用钩子的示例
const Note = () => {
const note = useSelector(state => state.note.note)
const dispatch = useDispatch()
useEffect(() => {
dispatch(getNote())
}, [])
return ...
}
答案 1 :(得分:0)
我认为您应该使用props.getNote()并将其分派,一旦完成,您应该会很好。