我有应用程序写在pure React
上,我向服务器发出请求并获得响应-category list
。单击标题表asc-desc
时,可以按id
排序此列表。我需要将React应用的一小部分重新制作为Redux。
但是当我将此部分重新制作为redux
时,出现错误:
<th className="th-id" onClick={() => dispatch(changeSortAscDesc())}>ID <small>{sortAscDesc}</small></th>
第一个问题,我将编写重制为Redux的代码在_______________________________之后,下面我将写我的应用程序的一小部分,该应用程序是在纯React上编写的(在重新制作为redux之前),并且运行良好。
export const changeSortAscDesc = (prev) => ({
type: "SORT_ASC_DESC",
payload: prev
});
const initialState = {
sortAscDesc: "asc",
};
export function filterList(state = initialState, action) {
switch (action.type) {
case "SORT_ASC_DESC": {
const { payload } = action;
return {
...state,
sortAscDesc: payload.sortAscDesc == 'asc' ? 'desc' : 'asc'
};
}
default:
return state;
}
}
export default (props) => {
const sortAscDesc = useSelector(state => state.filterListReducer.sortAscDesc);
const dispatch = useDispatch();
return (
<table>
<thead>
<tr>
<th></th>
<th onClick={() => dispatch(changeSortAscDesc())}>ID <small>{sortAscDesc}</small></th>
<th>TITLE</th>
</tr>
</thead>
<tbody className="table-body">
{props.dataAttribute.map(item => (
<tr key={item.id}>
<td>{item.id} </td>
<td>{item.title} </td>
</tr>
))}
</tbody>
</table>
);}
const Home = () => {
const [value, setValue] = useState({
listCategory: [],
sortAscDesc: "asc",
});
// Here useEffect and fetch function, but I dont write it, because it not related with my question
const changeSortAscDesc = () => {
setValue((prev) => ({
...prev,
sortAscDesc: prev.sortAscDesc == 'asc' ? 'desc' : 'asc'
}));
};
return (
<div>
<Table dataAttribute={value.listCategory}
changeSortAscDesc={changeSortAscDesc}
sortAscDesc={value.sortAscDesc}
/>
</div>
);
export default (props) => {
const sortAscDesc = useSelector(state => state.filterListReducer.sortAscDesc);
const dispatch = useDispatch();
return (
<table>
<thead>
<tr>
<th></th>
<th onClick={props.changeSortAscDesc}>ID <small>{props.sortAscDesc}</small></th>
<th>TITLE</th>
</tr>
</thead>
<tbody className="table-body">
{props.dataAttribute.map(item => (
<tr key={item.id}>
<td>{item.id} </td>
<td>{item.title} </td>
</tr>
))}
</tbody>
</table>
);}
您不会通过操作分派任何有效负载-
<th onClick={() => dispatch(changeSortAscDesc(dataThatNeedsToBePassed))}>ID <small>{sortAscDesc}</small></th> //pass data as parameter
编辑-您可以使它以这种方式工作-
const initialState = {
sortAscDesc: "asc",
};
export function filterList(state = initialState, action) {
switch (action.type) {
case "SORT_ASC_DESC": {
const { payload } = action; // no need //
return {
...state,
sortAscDesc: state.sortAscDesc == 'asc' ? 'desc' : 'asc'
};
}
default:
return state;
}
}
您可以从操作中删除有效载荷-
export const changeSortAscDesc = () => ({
type: "SORT_ASC_DESC",
payload: prev// no need //
});