redux를 사용하여 API에서 데이터를 가져 오는 기능 구성 요소가 있습니다.
const useFetching = (someFetchActionCreator) => {
const dispatch = useDispatch();
useEffect(() => {
dispatch(someFetchActionCreator());
}, [])
}
구성 요소 :
export function Trips(props) {
const trips = useSelector(state => state.trips);
useFetching(fetchTrips)
...
...
}
썽크 :
export const fetchTrips = () => (dispatch) =>
axios.get("/api/v1/trips")
.then(response => dispatch(addTrips(response.data)))
export const addTrips = trips => ({
type: ADD_TRIPS,
payload: trips
})
감속기 :
function tripsReducer(state = INITIAL_STATE, action) {
console.log(action)
if (action.type === ADD_TRIPS) {
return Object.assign({}, state, {
trips: state.trips.concat(action.payload)
});
}
return state
}
내 감속기가 호출됩니다. 가져온 데이터가 발송 된 후 UI를 업데이트하려면 어떻게해야합니까? 내 렌더링이 다시 호출되지 않습니다.
첫 번째 옵션 : 후크 사용
실제로 사용 React
하고 react-redux
있습니다. trips
나중에 구성 요소에서 개체를 사용해야합니다 . 다음은 코드를 사용하는 샘플입니다.
import React, { useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { fetchTrips } from '../tripsActions';
const useFetching = (someFetchActionCreator) => {
const dispatch = useDispatch();
useEffect(() => {
dispatch(someFetchActionCreator());
}, []);
}
export function Trips(props) {
const trips = useSelector(state => state.trips);
useFetching(fetchTrips);
return (
<div>
<p>Total trips: {trips.length}</p>
</div>
);
}
두 번째 옵션 : 연결 사용
이것이 후크를 도입하기 전에 Redux 스토어 상태에 연결하는 방법이었습니다.
당신이 사용하는 것처럼 반응-돌아 오는 이 쉽게 사용하여 수행 할 수있는 connect()
기능. 또한 mapStateToProps()
구성 요소가 필요로하는 저장소에서 데이터의 일부를 선택하는 mapDispatchToProps()
함수 와 디스패치 할 작업에 액세스 할 수 있는 함수를 제공해야합니다.
이 Trips
접근 방식을 사용하면 구성 요소가 다음과 같이 보입니다.
import React from 'react';
import { connect } from 'react-redux';
import { fetchTrips } from '../tripsActions';
const mapStateToProps = (state) => {
return {
// will be available as props.trips
trips: state.trips
}
}
const mapDispatchToProps = (dispatch) => {
return {
// will be available as props.fetch()
fetch: () => dispatch(fetchTrips)
}
}
const function Trips(props) {
this.props.fetch();
// some other code. Example:
return (
<div>
<p>Total trips: {this.props.trips.length}</p>
</div>
);
}
export default connect(mapStateToProps)(Trips);
mapStateToProps()
Redux 저장소 상태를 수신하고 구성 요소에서 해당 필드를 소품으로 사용할 수있는 객체를 반환합니다. 이미 사용 props.trips
하고 있으므로 해당 필드를 Redux 상태 trips
필드 의 업데이트 된 값에 매핑했습니다 .
connect()
구성 요소에 대한 호출 은 연결된 구성 요소를 제공합니다 . 그리고 후자는 원래 구성 요소가 아닌 내 보내야합니다. 다른 구성 요소를 만들지 않으므로 구성 요소를 계속 Trips
정상적으로 사용합니다 .
이제 소품이 업데이트 될 때 구성 요소가 다시 렌더링됩니다.
connect()
및 mapStateToProps()
및 mapDispatchToProps()
함수 의 사용을 더 잘 이해하기 위해 react-redux 문서를 살펴볼 수 있습니다 .
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다