繁体   English   中英

react-admin:调度动作以存储来自动态请求的元数据

[英]react-admin: dispatch action to store meta data from dynamic request

你好这个问题是继续这一个

我通过ajax请求动态获取我的路由(在官方文档“在运行时声明资源” 这篇文章之后),我正在使用异步函数从ajax请求返回资源列表。

分配存储元数据的动作的最佳方法是什么,我在redux中形成ajax请求,以便以后访问?

此外,当用户尚未登录时,此功能将不会返回任何内容,登录后,用户将可以访问几个资源。 重新加载资源的最佳方法是什么?

为了使这个工作,我添加了一个私有变量,我存储问题中提到的数据,我通过另一个函数访问它,我从该文件导出。

这给了我我需要的东西,但我不知道这是不是最好的方法。

最好的选择是使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM