When a component changes through a Redux action, the ques
appear to be entered and the reminder has changed. However, if imported into mapStateToProps
from another component, the value does not change and only the empty value is entered. Why? This is my github
import { combineReducers } from 'redux';
import { INFOMATION } from "../actions";
const postInitialState ={
id: '',
ques: '',
ans1: '',
ans2: ''
};
const postInfomation = (state = postInitialState, action) => {
switch (action.type) {
case INFOMATION:
console.log(state)
return Object.assign({}, state, {
id: action.id,
ques: action.ques,
ans1: action.ans1,
ans2: action.ans2
});
default:
return state
}
};
const postApp = combineReducers({
postInfomation
});
export default postApp;
import React, {Component, Fragment} from 'react';
import { connect } from 'react-redux';
class Vote extends Component {
render() {
return (
<Fragment>
<h1>qwe</h1>
<h1>{this.props.id}</h1>
<h1>{this.props.ques}</h1>
</Fragment>
)
}
}
let mapStateToProps = (state) => {
console.log(state)
return {
id: state.postInfomation.id,
ques: state.postInfomation.ques,
ans1: state.postInfomation.ans1,
ans2: state.postInfomation.ans2
};
}
Vote = connect(mapStateToProps) (Vote);
export default Vote;
Your code is functioning, but by visiting the /vote
page your app reloads and the state is reinitialized. You can spot this with the Redux Devtools extension , which shows the @@INIT
call when navigating.
If you add a <Link to="/vote">Vote</Link>
to navigate to the /vote
route you'll notice the state remains. If you use the HashRouter
you won't have this problem because the browser won't reload the page.
--
Do note that there are more issues with your state logic. Everytime a user updates one of your inputfields you update the redux store, and your local state. But when the user subsequently submits the form you only update the id of the local state, that id is only put in the redux state if the user changes one of the input fields again.
I would only update the redux state after submitting the form. Keep the values in local state until that time. Also move your axios call to a service that you call via your action with redux-thunk
.
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.