[英]react-admin: dispatch action to store meta data from dynamic request
為了使這個工作,我添加了一個私有變量,我存儲問題中提到的數據,我通過另一個函數訪問它,我從該文件導出。
這給了我我需要的東西,但我不知道這是不是最好的方法。
最好的選擇是使用redux-saga
。 https://redux-saga.js.org/docs/introduction/BeginnerTutorial.html
然后
export function* async() {
yield fetch(); //your Ajax call function
yield put({ type: 'INCREMENT' }) //call your action to update your app
}
如果你不能使用redux-saga,我喜歡你的私有變量解決方案。 你應該繼續這樣做。
https://github.com/redux-utilities/redux-actions
redux-actions設置非常簡單。 配置存儲,然后您可以在單個文件中設置每個狀態值:
import { createAction, handleActions } from 'redux-actions' let initialState = { myValue: '' } export default handleActions({ SET_MY_VALUE: (state, action) => ({...state, myValue: action.payload}) }) export const setMyValue = createAction('SET_MY_VALUE') export const doSomething = () => { return dispatch => { doFetch().then(result => { if (result.ok) dispatch(setMyValue(result.data)) }) } }
然后在組件中,您只需連接即可訪問狀態值
import React from 'react' import PropTypes from 'prop-types' import { connect } from 'react-redux' class MyComponent extends React.Component { render = () => ( <span>{this.props.myValue}</span> ) } MyComponent.propTypes = { myValue: PropTypes.string.isRequired } const mapStateToProps = (state) => ({ myValue: state.myState.myValue }) const mapDispatchToProps = () => ({}) export default connect(mapStateToProps, mapDispatchToProps)(MyComponent)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.