useEffect () 호출시 Redux 작업 (db에서 가져 오기)이 실행되지 않음

미르코 오 리치

Redux를 배우기 위해 eCommerce 웹 사이트를 구축하려고합니다.

현재 구성 요소가 마운트 될 때 카테고리를 가져 오려고합니다. 기능적 구성 요소를 사용하고 있으므로 useEffect () 메서드를 호출하여이 작업을 수행 할 수 있음을 이해했습니다.

또한 json-server를 REST API로 사용하고 있습니다.

나는 내 인핸서를 구성하여 스토어 (개발 도구 및 썽크)로 전달하고 액션, 리듀서 등을 만들었습니다.

내 문제는 구성 요소가 마운트 될 때 작업이 실행되지 않는다는 것입니다.

미들웨어와 가져 오기 요청을 도입하기 전에 NB는 모든 것이 잘 작동했습니다. 또한 가져 오기 요청이 성공 했는지도 고려하십시오.

다음은 관련된 코드입니다.

'src / index.js'

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import { createStore, applyMiddleware, compose } from 'redux'
import { Provider } from 'react-redux'
import rootReducer from './reducers'
import thunk from 'redux-thunk'

const composedEnhancers = compose(applyMiddleware(thunk), window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__())

const store = createStore(
  rootReducer, /* preloadedState, */
  composedEnhancers
);

ReactDOM.render(
  <Provider store={store}>
    <React.StrictMode>
      <App />
    </React.StrictMode>
  </Provider>,
  document.getElementById('root')
);

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.

serviceWorker.unregister();

'actions / index.js'의 작업 유형 :

export const FETCH_CATEGORIES = 'FETCH_CATEGORIES'

'actions / index.js'의 액션 생성자 :

export const fetchCategories = () => (dispatch) => {
    fetch("http://localhost:7000/categories")
        .then(response => response.json())
        .then(categories => {
            return {
                type: FETCH_CATEGORIES,
                payload: categories
            }
        })

}

'reducers / index.js'

import * as actions from './../actions'

const initState = {
    categories: [],
    currentCategory: 'any',
    toggler: 'hidden'
}

const rootReducer = (state = initState, action) => {
    switch (action.type) {
        case actions.SELECT_CATEGORY:
            return { ...state, currentCategory: action.payload.value }
        case actions.FETCH_CATEGORIES:
            return { ...state, categories: action.payload }
        case actions.TOGGLE:
            return { ...state, toggler: action.payload.toggler }
        default:
            return state
    }
}

export default rootReducer

'Filter.js'구성 요소

import React, { useEffect } from 'react';
import { connect } from 'react-redux'
import { selectCategory, fetchCategories } from '../../../../actions'



const Filter = (props) => {

    // const [minPrice, setMinPrice] = useState(0)
    // const handleMinPrice = event => {
    //     setMinPrice(event.target.value)
    // }

    // const [maxPrice, setMaxPrice] = useState(0)
    // const handleMaxPrice = event => {
    //     setMaxPrice(event.target.value)
    // }

    // const [department, setDepartment] = useState("select")
    // const handleDepartment = event => {
    //     console.log(event.target.value)
    //     setDepartment(event.target.value)
    // }
    // console.log(props);


    const handleChange = event => {
        event.preventDefault()
        props.selectCategory(event.target.value)
    }

    useEffect(() => {
        props.fetchCategories()
    })


    return (
        <div className="filter-form col-12">
            <form id="filter-category">
                <label htmlFor="category">Category</label>
                <select className="col-12" id="category" name="category" size="5" value={props.currentCategory} onChange={(event) => handleChange(event)}>
                    {props.categories.map(category => <option key={category.value} value={category.value}>{category.name}</option>)}
                </select>
            </form>
            {props.currentCategory !== 'any' && <form id="filter-department">
                <label htmlFor="department">Department</label>
                <select className="col-12" id="department" name="department" size="5" value='{department}' onChange='{handleDepartment}'>
                    <option value="select">--- Select ---</option>
                    <option value="desktop PCs">Desktop PCs</option>
                    <option value="laptops">Laptops</option>
                    <option value="gamepads">Gamepads</option>
                    <option value="headphones">Headphones</option>
                    <option value="microphones">Microphones</option>
                    <option value="keyboards">Keyboards</option>
                </select>
            </form>}
            {/* <form id="filter-price">
                <label htmlFor="minimum-price">Min. Price: {minPrice}£</label>
                <input type="range" min="1" max="100" value={minPrice} className="slider col-xs-12" id="minimum-price" onChange={handleMinPrice} />
                <label htmlFor="maximum-price">Max. Price: {maxPrice}£</label>
                <input type="range" min="100" max="1000" value={maxPrice} className="slider col-xs-12" id="maximum-price" onChange={handleMaxPrice} />
            </form> */}
        </div>
    );
}

const mapStateToProps = (state) => {
    return {
        categories: state.categories,
        currentCategory: state.currentCategory
    }
}

const mapDispatchToProps = (dispatch) => {
    return {
        selectCategory: (value) => {
            dispatch(selectCategory(value))
        },
        fetchCategories: () => {
            dispatch(fetchCategories())
        }

    }
}

export default connect(mapStateToProps, mapDispatchToProps)(Filter);

또한 여기에 'db.json'이 있습니다.

{
  "categories": [
    {
      "id": "1",
      "value": "any",
      "name": "--- Any ---",
      "departments": []
    },
    {
      "id": "2",
      "value": "computers-and-accessories",
      "name": "Computers and Accessories",
      "departments": [
        {
          "id": "1",
          "value": "desktop-pc",
          "name": "Desktop PCs"
        },
        {
          "id": "2",
          "value": "laptops",
          "name": "Laptops"
        },
        {
          "id": "3",
          "value": "keyboards",
          "name": "Keyboards"
        },
        {
          "id": "4",
          "value": "headphones",
          "name": "Headphones"
        },
        {
          "id": "5",
          "value": "mouses",
          "name": "Mouses"
        },
        {
          "id": "6",
          "value": "gamepads",
          "name": "Gamepads"
        }
      ]
    },
    {
      "id": "3",
      "value": "fashion",
      "name": "Fashion",
      "departments": [
        {
          "id": "1",
          "value": "dresses",
          "name": "dresses"
        },
        {
          "id": "2",
          "value": "shoes",
          "name": "Shoes"
        },
        {
          "id": "3",
          "value": "pants",
          "name": "Pants"
        },
        {
          "id": "4",
          "value": "sunglasses",
          "name": "Sunglasses"
        },
        {
          "id": "5",
          "value": "handbags",
          "name": "Handbags"
        },
        {
          "id": "6",
          "value": "hats",
          "name": "Hats"
        }
      ]
    },
    {
      "id": "4",
      "value": "digital-music",
      "name": "Digital Music",
      "departments": [
        {
          "id": "1",
          "value": "rock",
          "name": "Rock"
        },
        {
          "id": "2",
          "value": "pop",
          "name": "Pop"
        },
        {
          "id": "3",
          "value": "house-and-techno",
          "name": "House and Techno"
        },
        {
          "id": "4",
          "value": "trap",
          "name": "Trap"
        },
        {
          "id": "5",
          "value": "indie",
          "name": "Indie"
        },
        {
          "id": "6",
          "value": "hip-hop",
          "name": "Hip-Hop"
        }
      ]
    },
    {
      "id": "5",
      "value": "house",
      "name": "House",
      "departments": [
        {
          "id": "1",
          "value": "kitchen",
          "name": "kitchen"
        },
        {
          "id": "2",
          "value": "garden",
          "name": "Garden"
        },
        {
          "id": "3",
          "value": "bedroom",
          "name": "Bedroom"
        },
        {
          "id": "4",
          "value": "bathroom",
          "name": "Bathroom"
        },
        {
          "id": "5",
          "value": "livingroom",
          "name": "Livingroom"
        },
        {
          "id": "6",
          "value": "cleaning",
          "name": "Cleaning"
        }
      ]
    },
    {
      "id": "6",
      "value": "grocery",
      "name": "Grocery",
      "departments": [
        {
          "id": "1",
          "value": "vegetables",
          "name": "Vegetables"
        },
        {
          "id": "2",
          "value": "pasta and rice",
          "name": "Pasta and Rice"
        },
        {
          "id": "3",
          "value": "snacks",
          "name": "Snacks"
        },
        {
          "id": "4",
          "value": "canned-food",
          "name": "Canned Food"
        },
        {
          "id": "5",
          "value": "frozen",
          "name": "Frozen"
        },
        {
          "id": "6",
          "value": "dairy",
          "name": "Dairy"
        }
      ]
    }
  ]
}

내가 여기서 무엇을 놓치고 있습니까?

Grant Singleton

감속기 FETCH_CATEGORIES를 실행하는 작업에서 다음과 같이 디스패치를 ​​시도하십시오.

export const fetchCategories = () => (dispatch) => {
    fetch("http://localhost:7000/categories")
        .then(response => response.json())
        .then(categories => {
            // **Changes start here
            dispatch ({
                type: FETCH_CATEGORIES,
                payload: categories
            })
            // **Changes end here
        })

}

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

Redux : 비동기 작업 생성자가 호출되지 않음

분류에서Dev

반응 후크-작업이 전달 된 후 useEffect가 호출되지 않음

분류에서Dev

감속기가 실행중인 작업에 대한 상태를 업데이트하지 않아서 redux 저장소 / 상태가 업데이트되지 않음

분류에서Dev

Windows 스레딩-디버그 작업 릴리스가 실행되지 않음-시작시 스레드에서 값 가져 오기 시도

분류에서Dev

Redux onClick 작업이 구성 요소에서 실행되지 않음, 오류 또는 콘솔 오류 없음

분류에서Dev

redux-thunk를 사용한 비동기 API 호출로 인해 redux props가 변경되면 UseEffect가 실행되지 않습니다.

분류에서Dev

호출기에서 yii cgridview afterAjaxUpdate가 실행되지 않음

분류에서Dev

내 Redux 설정에서 감속기가 호출되지 않음

분류에서Dev

showAllSteps : false 인 경우 호출 된 기능 파일의 작은 오이 단계가 오이 병렬 실행 보고서에 표시되지 않습니다.

분류에서Dev

Redux 작업이 두 번째로 호출되지 않음

분류에서Dev

useEffect () 체인 함수 호출이 업데이트 된 redux 상태를 가져 오지 못함

분류에서Dev

redux 구조를 사용하여 작업을 실행 한 후 구성 요소가 react-native에서 업데이트되지 않음

분류에서Dev

axios 호출에서 redux 기능 후 코드가 작동하지 않음

분류에서Dev

장기 실행 작업 중에 진행률 스피너가 표시되지 않음

분류에서Dev

메서드 내에서 가져 오기 및 호출 기능이 작동하지 않음

분류에서Dev

Azure Cosmos DB 에뮬레이터가 실행되지 않음-시작된 후 오류 발생

분류에서Dev

Azure 클라우드 서비스 시작 작업이 실행되지 않음

분류에서Dev

useEffect에서 호출 될 때 useState setter가 상태를 업데이트하지 않음

분류에서Dev

Hadoop 작업 추적기 및 작업 추적기가 Ubuntu 13.10에서 실행되지 않음

분류에서Dev

RESTKit : NSFetchResultsController가 처음 실행시 업데이트되지 않음

분류에서Dev

Javascript 가져 오기를 사용하여 Django Rest API 호출에 본문이 게시되지 않음

분류에서Dev

redux의 작업을 사용하여 useEffect 내부 데이터 가져 오기

분류에서Dev

React Redux onBlur 이벤트가 Safari 및 Firefox에서 실행되지 않음

분류에서Dev

실패한 API 가져 오기 요청 후 useEffect 다시 호출

분류에서Dev

Microsoft Azure 시작 작업이 실행되지 않음

분류에서Dev

오류 발생 : js 호출을 실행할 수 없음 : 시뮬레이터에서 실행하는 동안 _fbBatchedBridge가 정의되지 않았습니다.

분류에서Dev

Spark / Hadoop 작업이 parralel에서 실행되지 않음

분류에서Dev

Celery 작업 내에서 API 호출이 반환되지 않음

분류에서Dev

React useEffect 정리 함수가 useEffect 콜백 직후에 실행되고 다시는 실행되지 않는 이유는 무엇입니까?

Related 관련 기사

  1. 1

    Redux : 비동기 작업 생성자가 호출되지 않음

  2. 2

    반응 후크-작업이 전달 된 후 useEffect가 호출되지 않음

  3. 3

    감속기가 실행중인 작업에 대한 상태를 업데이트하지 않아서 redux 저장소 / 상태가 업데이트되지 않음

  4. 4

    Windows 스레딩-디버그 작업 릴리스가 실행되지 않음-시작시 스레드에서 값 가져 오기 시도

  5. 5

    Redux onClick 작업이 구성 요소에서 실행되지 않음, 오류 또는 콘솔 오류 없음

  6. 6

    redux-thunk를 사용한 비동기 API 호출로 인해 redux props가 변경되면 UseEffect가 실행되지 않습니다.

  7. 7

    호출기에서 yii cgridview afterAjaxUpdate가 실행되지 않음

  8. 8

    내 Redux 설정에서 감속기가 호출되지 않음

  9. 9

    showAllSteps : false 인 경우 호출 된 기능 파일의 작은 오이 단계가 오이 병렬 실행 보고서에 표시되지 않습니다.

  10. 10

    Redux 작업이 두 번째로 호출되지 않음

  11. 11

    useEffect () 체인 함수 호출이 업데이트 된 redux 상태를 가져 오지 못함

  12. 12

    redux 구조를 사용하여 작업을 실행 한 후 구성 요소가 react-native에서 업데이트되지 않음

  13. 13

    axios 호출에서 redux 기능 후 코드가 작동하지 않음

  14. 14

    장기 실행 작업 중에 진행률 스피너가 표시되지 않음

  15. 15

    메서드 내에서 가져 오기 및 호출 기능이 작동하지 않음

  16. 16

    Azure Cosmos DB 에뮬레이터가 실행되지 않음-시작된 후 오류 발생

  17. 17

    Azure 클라우드 서비스 시작 작업이 실행되지 않음

  18. 18

    useEffect에서 호출 될 때 useState setter가 상태를 업데이트하지 않음

  19. 19

    Hadoop 작업 추적기 및 작업 추적기가 Ubuntu 13.10에서 실행되지 않음

  20. 20

    RESTKit : NSFetchResultsController가 처음 실행시 업데이트되지 않음

  21. 21

    Javascript 가져 오기를 사용하여 Django Rest API 호출에 본문이 게시되지 않음

  22. 22

    redux의 작업을 사용하여 useEffect 내부 데이터 가져 오기

  23. 23

    React Redux onBlur 이벤트가 Safari 및 Firefox에서 실행되지 않음

  24. 24

    실패한 API 가져 오기 요청 후 useEffect 다시 호출

  25. 25

    Microsoft Azure 시작 작업이 실행되지 않음

  26. 26

    오류 발생 : js 호출을 실행할 수 없음 : 시뮬레이터에서 실행하는 동안 _fbBatchedBridge가 정의되지 않았습니다.

  27. 27

    Spark / Hadoop 작업이 parralel에서 실행되지 않음

  28. 28

    Celery 작업 내에서 API 호출이 반환되지 않음

  29. 29

    React useEffect 정리 함수가 useEffect 콜백 직후에 실행되고 다시는 실행되지 않는 이유는 무엇입니까?

뜨겁다태그

보관