我在创作者中定义了一个动作:
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>
}
所以我想弄清楚如何在reducer函数中抓住传入的参数?这就是减速器的样子:
export const reducer: Reducer<SubmitLinkState> = (state: SubmitLinkState, action: KnownAction) => {...}
如果这不是正确的工作流程,我该怎么办?最终目标是有一个文本框,并且提交按钮会将该文本框的内容发送到reducer。
答案 0 :(得分:1)
您可以将网址作为动作参数传递,例如
export const actionCreators = {
submitlink: (url: string) => <SubmitLinkAction>{ type: 'SUBMIT_LINK', url}
}
然后在reducer中将其作为action.url
export const reducer: Reducer<SubmitLinkState> = (state: SubmitLinkState, action: KnownAction) => {
...
console.log(action.url);
}
答案 1 :(得分:0)
您可以使用操作数据将变量传递给减速器。
假设您需要构建 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: {}
}
然后你可以像这样定义一个 Action 来更新表数据,注意我们将 Store 名称作为参数传递,以便我们更新正确的数据表(因为你的应用程序中可能有多个数据表)
>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`
})
}
}
之后你可以有一个像这样的Reducer:
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
}
}