我正在使用Redux设置Ag-Grid React,并且需要异步检索我的rowData。
我正在为此使用redux-saga,并正确获取了数据,并正确地将其返回到包含网格的组件的属性。但是,由于数据是异步的,因此网格已经被渲染,并且使用rowData渲染网格不会导致行包含数据。
组件
import { fetchDataRequest } from '../actions/index';
class GridComponent extends Component {
componentDidMount() {
this.props.dispatch(fetchDataRequest());
}
render() {
return (
<div>
<AgGridReact
rowData={this.props.data.items}
columnDefs={...}
defaultColDef={...}
/>
</div>
)
}
}
function mapStateToProps(state) {
const { data } = state;
const { isFetching, items } = data ?
{ isFetching: false, items: data.items } :
{ isFetching: true, items: []};
return {
isFetching,
items,
}
}
const ConnectedGridComponent = connect(mapStateToProps)(GridComponent);
export default ConnectedGridComponent;
容器索引
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import GridComponent from '../components/GridComponent'
import configureStore from '../store/configureStore';
import rootSaga from '../sagas/sagas';
const store = configureStore();
store.runSaga(rootSaga);
ReactDOM.render(
<Provider store={store}>
<GridComponent />
</Provider>,
document.getElementById('gridcomponent')
);
减速器
import { combineReducers } from 'redux':
import { FetchDataActions } from '../actions/index';
const data = (state = {
isFetching: false,
items: []
}, action) => {
switch (action.type) {
case FetchDataActions.FETCH_DATA_REQUEST:
return {
...state,
isFetching: true
};
case FetchDataActions.FETCH_DATA_SUCCESS:
return {
...state,
isFetching: false,
items: action.data.list,
lastUpdated: action.lastUpdated
};
default:
return state
}
};
const rootReducer = combineReducers( {
data
});
export default rootReducer
ConfigureStore
import { createStore, applyMiddleware } from 'redux';
import createSagaMiddleware from 'redux-saga';
import rootReducer from '../reducers/index';
export default function configureStore() {
const sagaMiddleware = createSagaMiddleware();
return {
...createStore(rootReducer, applyMiddleware(sagaMiddleware)),
runSaga: sagaMiddleware.run,
}
}
Sagas
import { call, put, fork } from 'redux-saga/effects';
import * as actions from '../actions/index';
export function fetchDataApi() {
return fetch('/path/to/api')
.then(response => response.json())
.then(json => json);
}
export function* fetchData() {
yield put(actions.fetchDataRequest());
const data = yield call(fetchDataApi);
yield put(actions.fetchDataSuccess(data));
}
export function* startup() {
yield fork(fetchData);
}
export default function* root() {
yield fork(startup);
}
动作
export const FetchDataActions = {
FETCH_DATA_REQUEST: 'FETCH_DATA_REQUEST',
FETCH_DATA_FAILURE: 'FETCH_DATA_FAILURE',
};
export function fetchDataRequest() {
return {
type: FetchDataActions.FETCH_DATA_REQUEST
}
}
export function fetchDataSuccess(data) {
return {
type: FetchDataActions.FETCH_DATA_SUCCESS,
data: data,
lastUpdated: Date.now(),
}
}
过去,异步调用完成后,我们已经使用了Grid API的setRowData(rowData)方法添加数据。在这种情况下,这似乎不起作用,因为恢复完成时redux不会告诉组件,而且我不确定如何将Grid api传递给sagas。