IT이야기

반응 후크가 있는 Redex 작업 대기 중

cyworld 2022. 3. 26. 16:37
반응형

반응 후크가 있는 Redex 작업 대기 중

데이터 가져오기가 발생할 때 로드 컴포넌트를 보여주기 위해 양식 제출을 처리하려고 한다.데이터를 내 컴퓨터에 로드했을 때 표시하려고 함Redux저장하다

지금 당장, 나는 내 컴포넌트를 사용하도록 설정했다.React훅. 데이터가 내 안으로 로드되는 동안redux성공적으로 저장, 작업이 완료된 결과를 어떻게 "기다리는"지 잘 모르겠다.내 구성 요소의 모양을 단순화한 버전은 다음과 같다.

const DataPage = (props) => {

    const [isLoading, setIsLoading] = useState(false);
    const [isError, setError] = useState(false);

    useEffect(() => { // Reset Filters when dataSource changes...
        setError(false);
        setIsLoading(false);
    }, [dataSource]);

    const handleSubmit = (e, { dataSource }) => {

        e.preventDefault();
        setError(false)
        setIsLoading(true);

         //// IDEALLY THIS IS WHERE THE FIX WOULD GO? TURN THIS INTO ASYNC/AWAIT?
        props.fetchData({ dataSource, token: localStorage.JWT_TOKEN });
    };

    return (    
        <div className="dataPage">
            <form className="dataPage__filters" onSubmit={(e) => handleSubmit(e, { dataSource })}>
                <DataSelector dataSource={dataSource} setDataSource={setDataSource}/>
                <button className="button">
                   Search
                </button>
            </form>
            {isError && <div>Something went wrong...</div>}
            { isLoading ? ( <div>...Loading </div> ) : (
                <div className="dataPage__table">
                    <DataTable /> // This is connected to my redux-store separately through 'connect'
                </div>
            )}
        </div>
    );
};

const mapDispatchToProps = (dispatch) => ({
    fetchData: ({ dataSource, token }) => dispatch(startFetchData({ dataSource, token }))
});

export default connect(null, mapDispatchToProps)(DataPage);

관련 조치(Anternational Actions)startFetchData그리고setData)은 다른 파일에 위치하며, 다음과 같이 보인다.

export const setData = (data) => ({
    type: "SET_DATA",
    data
});

export const startFetchData = ({ dataSource, filter, filterTarget, token }) => {
    return (dispatch) => {

        axios.get(`${'http://localhost:8081'}/api/${dataSource}`, { headers: { authorization: token }})
        .then((res) => {
            dispatch(setData(result));
        });
    }
};

가능하다면 새로운 종속성을 도입하지 않고도 이 일을 할 수 있었으면 좋겠다.

TypeScript를 사용하는 사용자를 위한 참고 사항:원한다면await을 이용한 행동에 의해 반환된 약속.useDispatch()불필요한 것에 대해 불평하는 TypeScript를 볼 수 있다.await.

이 경우 올바른 타이핑을 추가하십시오(ThunkDispatch 참조).useDispatch제네릭으로

또한useEffect()비동기식 구문을 사용하여 다음을 마무리하십시오.async때문에 또 다른 폐쇄에 부호를 붙이다.useEffect()A을 기대하다voidReturn value와 Typecript는 그렇지 않으면 당신이 약속을 반환하는 것에 대해 불평한다.

const dispatch = useDispatch<ThunkDispatch<any, any, Action>>();

useEffect(() => {
  (async () => {
    const myResult = await dispatch(...);
    const anotherResult = await dispatch(...);
    // ...
  })();
});

나는 네가 환원제 텀블링 미들웨어를 사용하는 것을 추천한다.객체 대신 기능(비동기 기능 포함)을 수행할 수 있는 작업은 정말 쉽고 유용한 라이브러리 입니다.예를 들어보자.

스토어 js

import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers/index';
import api from './services/api';

// Note: this API requires redux@>=3.1.0
const store = createStore(
  rootReducer,
  // With extra argument, in this case, my API):
  applyMiddleware(thunk.withExtraArgument(api));
);


AuthDuck.js

이 오리에게 주기(동일한 파일에 있는 유형, 동작 및 환원기, 자세한 내용은 여기를 참조하십시오)

// ----------------------------------------------------------------
// Types
// ----------------------------------------------------------------
const Types = {
  SIGN_IN_START: 'SIGN_IN_START',
  SIGN_IN_SUCCESS: 'SIGN_IN_SUCCESS',
  SIGN_IN_FAIL: 'SIGN_IN_FAIL'
};

// ----------------------------------------------------------------
// Actions
// ----------------------------------------------------------------
const signin = function (user) {
  // LOOK HERE!
  // Redux Thunk able you to return a function instead of an object.
  return async function (dispatch, getState, api) {
    try {
      dispatch({ type: Types.SIGN_IN_START });
      const token = await api.access.signin(user);
      dispatch({ type: Types.SIGN_IN_SUCCESS, payload: token });
    } catch (error) {
      dispatch({ type: Types.SIGN_IN_FAIL, payload: error });
    }
  };
};

export const Actions = { signin };

// ----------------------------------------------------------------
// Reducers
// ----------------------------------------------------------------
export default function reducer(state, action) {
  switch (action.type) {
    case VeasyCalendarTypes.SIGN_IN_START:
      return { ...state, isLoading: true };
    case VeasyCalendarTypes.SIGN_IN_SUCCESS:
      return { ...state, isLoading: false, token: action.payload };
    case VeasyCalendarTypes.SIGN_IN_FAIL:
      return { ...state, isLoading: false, error: action.payload };
    default:
      return state;
  }
};

도움이 되었으면 좋겠는데, 당신의 케이스에 도움이 되었는지 알려줘 :)

안부 전합니다

참조URL: https://stackoverflow.com/questions/56499007/awaiting-redux-action-w-react-hooks

반응형