问题
How can I change value of currentPage state using onClick event? I would like to change value after click button with number of page.
Component:
import React from 'react';
import { connect } from 'react-redux';
import { setCurrentPage } from '../actions/pages';
const PageItem = ({ pageNumber }) => (
<li className="page-link"
onClick = {(e) => this.setCurrentPage(e) }
id = { pageNumber }>
{ pageNumber }
</li>
);
const mapStateToProps = (state) => {
return {
pages: state.pages.currentPage
};
};
const mapDispatchToProps = (dispatch) => ({
setCurrentPage: () => dispatch(setCurrentPage(pageNumber))
});
export default connect(mapStateToProps, mapDispatchToProps)(PageItem);
Reducer:
const pagesReducerDefaultState = {
currentPage: 1
};
export default (state = pagesReducerDefaultState, action) => {
switch (action.type) {
case 'SET_CURRENT_PAGE':
return action.currentPage;
default:
return state;
}
}
Action:
export const setCurrentPage = (currentPage) => ({
type: 'SET_CURRENT_PAGE',
currentPage
});
回答1:
I fixed some of your errors.
To begin with, I suppose that you have made a Provider
markup in your root Component and make an instance to a store (if you're not sure, send the content of the App.js file).
// component
const PageItem = ({ pageNumber, setCurrentPage }) => (
<li
className="page-link"
onClick={() => setCurrentPage(pageNumber)}
id={pageNumber}
>
{pageNumber}
</li>
);
const mapStateToProps = state => {
return {
page: state.currentPage
};
};
const mapDispatchToProps = {
setCurrentPage
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(PageItem);
const pagesReducerDefaultState = {
currentPage: 1
};
Some thoughts :
- you can't use
this
in a function, only in a class mapDispatchToProps
may be used with a simple litteral object (like I learned it recently). This is less verbose then, because you may only mention theaction creator
(in your example,setCurrentPage
)- you have send
setCurrentPage
in the props, so you can retrieve it like I wrote. Maybe ES6 is cryptic here, so the ES5 equivalent will be:
function PageItem(props) {
return (
<li
className="page-link"
onClick={() => props.setCurrentPage(props.pageNumber)}
id={props.pageNumber}
>
{props.pageNumber}
</li>
);
};
// reducer
const initialState = {
currentPage: 1
};
export const reducer = (state = initialState, action) => {
switch (action.type) {
case "SET_CURRENT_PAGE":
return {
currentPage: action.currentPage
};
default:
return state;
}
};
- your state is an object with a property
currentPage
. So your reducer must return this kind of object (soreturn action.currentPage
was not correct)
回答2:
Update your action like below. Action should be dispatched so that reducer can handle it..
export const setCurrentPage = (currentPage) => {
return (dispatch) => {
dispatch({type: 'SET_CURRENT_PAGE',currentPage);
}
}
来源:https://stackoverflow.com/questions/52699936/change-state-onclick-reactredux