将参数传递给化简器?



我在创建者中定义了一个这样的操作:

export const actionCreators = {
submitlink: (url: string) => <SubmitLinkAction>{ type: 'SUBMIT_LINK' }
}

在调用它的组件中:

public render() {
return <div>
<div>{this.props.url}</div>
<button onClick={() =>
{
this.props.submitlink("google.com");
}}>submit</button>
</div>
}

所以我试图弄清楚如何在减速器函数中抓取传入的 thea rgument?这是减速器的样子:

export const reducer: Reducer<SubmitLinkState> = (state: SubmitLinkState, action: KnownAction) => {...}

另外,如果这不是正确的工作流程,我该怎么办?最终目标是有一个文本框,提交按钮将文本框的内容发送到化简器。

您可以将 url 作为操作参数传递,例如

export const actionCreators = {
submitlink: (url: string) => <SubmitLinkAction>{ type: 'SUBMIT_LINK', url}
}

然后在减速器中将其作为action.url

export const reducer: Reducer<SubmitLinkState> = (state: SubmitLinkState, action: KnownAction) => {
...
console.log(action.url);
}

您可以使用操作数据将变量传递给化简器。

假设您需要构建 1 个组件来管理所有数据表服务器端翻转逻辑:

您可以定义如下初始状态:

// ** Initial State
const initialState = {
rowsPerPage: 2,
totalItems: 0,
rows: [],
totalPages: 0,
currentPage: 0,
columns: [],
selectedClient: false,
isLoading: false,
searchValue: '',
apiURL: `${process.env.REACT_APP_BACKEND_API_ADDR}test`,
extraRequestParams: {}
}

然后,您可以定义一个操作来更新表数据,如下所示,请注意,我们将存储名称作为参数传递,以便我们更新正确的数据表(因为您的应用中可能有多个数据表(

import axios from 'axios'
//Default Table Actions
export const updateRows = ({ storeName }) => {
return async (dispatch, getState) => {
dispatch({
storeName,
type: `${storeName}-ENABLE_LOADING`
})
const { rowsPerPage, currentPage, selectedClient, searchValue, extraRequestParams } =
getState()[storeName]
const response = await axios.get(getState()[storeName].apiURL, {
params: {
rowsPerPage,
currentPage,
selectedClient,
searchValue,
extraRequestParams
}
})
dispatch({
storeName,
type: `${storeName}-UPDATE_ROWS`,
data: response.data
})
dispatch({
storeName,
type: `${storeName}-DISABLE_LOADING`
})
}
} 

之后,您可以拥有这样的减速器:

const DatatablesReducer = (state = initialState, action) => {
switch (action.type) {
case `${action.storeName}-UPDATE_ROWS`:
return {
...state,
...action.data
}
case `${action.storeName}-ENABLE_LOADING`:
return {
...state,
isLoading: true
}
case `${action.storeName}-DISABLE_LOADING`:
return {
...state,
isLoading: false
}
case `${action.storeName}-CHANGE_PAGE`:
return {
...state,
currentPage: action.data
}
case `${action.storeName}-CHANGE_ROWS_PER_PAGE`:
return {
...state,
rowsPerPage: action.data
}
case `${action.storeName}-CHANGE_SEARCH_VALUE`:
return {
...state,
searchValue: action.data
}
case `${action.storeName}-CHANGE_APIURL_VALUE`:
return {
...state,
apiURL: action.data
}
case `${action.storeName}-CHANGE_EXTRAREQUEST_PARAMS`:
return {
...state,
extraRequestParams: action.data
}
default:
return state
}
}

最新更新