0

我正在尝试从 django REST api 获取,但调度操作减速器不起作用。我正在使用 Material UI、Hooks、Redux。

动作减速器代码:

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);

我跟踪了代码未运行的位置,它位于“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

4

2 回答 2

1

问题是您没有调用为您传递的注入getNote,而是调用您导入的原始函数。connectprops

您可以connect在功能组件中使用,但react-redux也可以为您提供可以替换HOCuseSelector钩子useDispatch connect

使用示例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 ...
}
于 2019-12-28T17:22:37.440 回答
0

我认为你应该使用 props.getNote() 并发送它,一旦你这样做,你应该会很好。

于 2019-12-29T08:32:40.153 回答