I have two components reactjs , I create an state redux to handle this state from two components .
`appcomponent.js
import React, { Component } from 'react';
import { createStore } from 'redux';
import { connect } from 'react-redux';
//reducer
export function get_user(state=[], action) {
switch (action.type) {
case 'ADD_USER':
return [
{user:action.user}
];
default:
return state;
}
}
class appcomponent extends Component {
constructor(props) {
super(props);
this.state = {Users:[]};
//this.addUser=this.addUser.bind(this);
this.onFormSubmit=this.onFormSubmit.bind(this);
this.get=this.get.bind(this);
}
get(){
console.log(this.props.r);
}
onFormSubmit() {
this.props.send('user');
}
render() {
return (
<div>
<br /><br /><br />
<button onClick={this.onFormSubmit}>redux</button><br /><br /><br /><br />
<button onClick={this.get}>REDUX</button>
</div>
)}
}
// action
export function addUser(user) {
return {
type: 'ADD_USER',
user,
};
}
function mapDispatchToProps (dispatch) {
return {
send: user => dispatch(addUser(user))
};
};
const mapStateToProps = (state, ownProps) => {
return { r:state};
};
export default connect(mapStateToProps,mapDispatchToProps)(appcomponent);
In this component when I click "redux" button then onclick "REDUX" button I get the state changed. In the other component I have this code :
class App extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div><h1>{this.props.user}</h1></div>
)
}}
const mapStateToProps = (state, ownProps) => {
return { user: state[0].user};//.user
};
function mapDispatchToProps (dispatch) {
return {
get: user => dispatch(addUser('username'))
};
};
export default connect(mapStateToProps,mapDispatchToProps)(App);
In the last component always I get the initial state created in index.js
var store = createStore(get_user,[{user:'hhhh'}]);
ReactDOM.render( <Provider store={store}>
Please who can help me ?
in the first component try use the following code
and on the second component use the following code
You only need to call createStore() once, preferably near the top of your component tree not in each component.
Assuming you wrap your app in a Provider (from redux) you'll have access to redux's central State via the mapStateToProps function (where you can assign state elements to a particular components props):
And then in a component: