I’ve followed this guide , a new state object with updated propery is returned, but nothing, the view doesn’t update.
/* Events component */
const mapStateToProps = (state) => {
return {
text: state.eventsReducer.text
}
}
/* eventsReducer */
const initialState = {
text: 'This is a text!'
}
const eventsReducer = (state = initialState, action) => {
switch (action.type) {
case 'CHANGE_TEXT':
console.log('Initial state:', state);
const newState = Object.assign({}, state, { text: 'This is a new text' });
console.log('New state:', newState);
return newState;
default:
return state;
}
}
export default eventsReducer;
Where I’m doing wrong?
sashko
September 2, 2016, 11:48pm
2
Can you show where you’re using connect
to attach the Redux data to your component?
Uhm, I’m not in a container, I’m in the same file of the component, may be this is the problem?
sashko
September 2, 2016, 11:51pm
4
Can you show where you define the component?
The path is: imports/ui/components/Events.js
The content of the component file is
import React from 'react';
import { connect } from 'react-redux';
import { changeText } from '../redux/actions';
class Events extends React.Component {
constructor(props) {
super(props);
this.text = props.text;
this.onClick = props.onClick;
}
render() {
return (
<div className="events-container">
<h2>Events</h2>
<a onClick={this.onClick}>Click Me</a>
<h3>{this.text}</h3>
</div>
);
}
}
const mapStateToProps = (state) => {
return {
text: state.eventsReducer.text
}
}
const mapDispatchToProps = (dispatch) => {
return {
onClick: () => {
dispatch(changeText())
}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Events);
sashko
September 2, 2016, 11:54pm
6
massimilianomarini:
this.text = props.text;
That’s the problem.
The constructor is only called once, when the component is rendered. You need to use this.props.text
in your render
function directly.
2 Likes
Yes! Now it works!
Thank you so much @sashko , both for the help and explanation!
1 Like
khb
December 17, 2018, 8:37pm
8
I know this is old as dirt but you SAVED me…
something so silly as generating your component with Component = {…props} = {}
and using “props” inside instead of “this.props”
props is passed in and not recalculated…
this.props is passed in from each new render…
slap Jeez!!!
thanks again!!