Resource code: http://hysterical-amusement.surge.sh/, under React-Redux 04 - User Provider to Connect Redux
Does anybody know why in following Redux code, the Redux knows that addMessage is an action and addMessage automatically becomes argument of parameter action in the messageReducer function even without any pre-setting?
2nd question, the messageReducer function always has state = [] as its argument, will this mean whenever the messageReducer fires, the messageReducer always takes empty state array as its first argument? and if after first call, and state becomes not empty, how could messageReducer still take state = [] as its argument when the state is not empty array?
// Redux Code:
const ADD = 'ADD';
const addMessage = (message) => {
return {
type: ADD,
message: message
}
};
const messageReducer = (state = [], action) => {
switch (action.type) {
case ADD:
return state.concat(action.message);
default:
return state;
}
};
const store = Redux.createStore(messageReducer);
// React Code:
class DisplayMessages extends React.Component {
constructor(props) {
super(props);
this.state = {
input: '',
messages: []
}
}
handleChange = (event) => {
this.setState({
input: event.target.value
});
}
submitMessage = () => {
const currentMessage = this.state.input;
this.setState({
input: '',
messages: this.state.messages.concat(currentMessage)
});
}
render() {
return (
<div>
<h2>Type in a new Message:</h2>
<input
value={this.state.input}
onChange={this.handleChange}/><br/>
<button onClick={this.submitMessage}>Submit</button>
<ul>
{this.state.messages.map( (message, idx) => {
return (
<li key={idx}>{message}</li>
)
})
}
</ul>
</div>
);
}
};
const Provider = ReactRedux.Provider;
class AppWrapper extends React.Component {
// change code below this line
render() {
return (
<Provider store = {store}>
<DisplayMessages/>
</Provider>
);
}
// change code above this line
};