this is the code
import { connect } from "react-redux";
import { useParams } from "react-router-dom";
import ExpenseForm from "./ExpenseForm";
import { editExpense, removeExpense } from '../actions/expenses';
import {useNavigate} from 'react-router-dom';
//import { withRouter } from "react-router-dom";
function EditExpensePage (props){
const { id } = useParams();
const navigate = useNavigate()
return(
<div>
<ExpenseForm
expense={props.expense}
onSubmit={(expense) =>{
props.dispatch(editExpense(id,expense))
navigate('/');
}}
/>
<button onClick={()=>{
props.dispatch(removeExpense({id: props.expense.id}));
navigate('/');
}}>Remove</button>
</div>
);
};
function MapStateToProps(state){
const { id } = useParams();
return{
expense: state.expenses.find((expense)=> expense.id === id)
};
};
export default connect(MapStateToProps)(EditExpensePage);
i am trying to edit an expense with an id so that it can render a component that has the edited item. so far everything is working but after editing the field the component doesnt rerender, it return an error on the console. this is the error Invalid hook call. Hooks can only be called inside of the body of a function component
The reason for the error is you have used useParams
inside MapStateToProps
which you can not use inside MapStateToProps
. You can do something like this:
function MapStateToProps(state,ownProps){
const { id } = ownProps.match.params;
return{
expense: state.expenses.find((expense)=> expense.id === id)
};
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.