0

我有一个自定义减速器和一个连接组件来更改其状态。现在我想将此状态用作列表元素的永久过滤器。我知道 List 元素连接到 redux 状态,所以我希望我能够通过 List 组件的 props 访问它,但找不到如何做到这一点的方法。

4

2 回答 2

0

List组件已连接,但不是您的。

import { connect } from "react-redux";

const MyList = ({ is_published, ...props }) => (
    <List {...props} filter={{ is_published }}>

    </List>
);

const mapStateToProps = state => ({
    is_published: state.myCustomReducer.is_published,
});

export default connect(mapStateToProps, undefined)(MyList);

编辑:

刚刚发现当这个道具改变时我们不会更新数据。这是一个错误,您可以打开一个关于它的问题。

同时,这里有一个解决方法:创建一个自定义 saga,监听您在自定义减速器旁边使用的任何操作(我将SET_IS_PUBLISHED在我的示例中调用它)。这个自定义传奇应该是您的过滤器putchangeListParams动作创建者。react-admin

它可能看起来像这样(未经测试):

import { takeEvery, put, select } from 'redux-saga/effects'
import { changeListParams } from 'react-admin'
import { SET_IS_PUBLISHED } from './isPublished'

const getCurrentListParams = (state, resource) => {
    const resourceState = state.admin.resources[resource]
    return resourceState.list.params
}

function handleSetPublished({ payload }) {
    const currentParams = yield select(getCurrentListParams)
    const newParams = {
        // Keep the current params
        ...currentParams,
        // Override the filter
        filter: {
            // Keep the current filter
            ...currentParams.filter,
            // Only override the is_published
            is_published: payload
        }
    }
    // Dispatch the action for the `posts` resource
    yield put(changeListParams('posts', newParams))
}

export default function* () {
    yield takeEvery(SET_IS_PUBLISHED, handleSetPublished)
}
于 2018-07-19T08:05:51.897 回答
0

只是为了把它带到 2021 年,你可以使用 useSelector redux hook 来掌握你的自定义状态:

import { useSelector } from 'react-redux';
const MyCustomThing = (props) => {
  const is_published = useSelector(state => state.customState.is_published);
}

为了完整起见,react-admin 为其组件提供了一个 customReducers<Admin>属性,因此您可以使用自定义值扩展 redux 状态:

const customStateReducer = (customState = { is_published: false }, { type, payload }) => {
  if (type === 'IS_PUBLISHED') customState.is_published = payload.is_published;
  return customState;
}

<Admin customReducers={{ customState: customStateReducer }} ...>
etc
于 2021-03-17T15:22:58.297 回答