Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React, { Component } from 'react';
- import { connect, Provider } from 'react-redux';
- import { createStore, compose } from 'redux';
- import { render } from 'react-dom';
- function capitalize(str) {
- return str.split('').map((s, i) => {
- if (i === 0) return s.toUpperCase();
- return s;
- }).join('');
- }
- function withState(state) {
- return function ComponentWithState(WrappedComponent) {
- return class extends Component {
- state = state;
- handleStateChange(key) {
- return (value = state[key], callback = null) => {
- return this.setState({ [key]: value }, callback);
- }
- }
- get stateHandlers() {
- return Object
- .keys(this.state)
- .reduce(
- (handlers, key) => {
- return {
- ...handlers,
- [`update${capitalize(key)}`]: this.handleStateChange(key),
- };
- },
- {}
- )
- }
- render() {
- return (
- <WrappedComponent
- {...this.stateHandlers}
- {...this.state}
- {...this.props}
- />
- );
- }
- }
- }
- }
- function App(props) {
- const newLastName = props.lastName === 'Xalambrí'
- ? 'Caeiro'
- : undefined;
- return (
- <h1
- onClick={props.handleClick(
- props.name.split('').reverse().join('')
- )}
- >
- hola {props.name} {props.lastName}
- <button onClick={() => props.updateLastName(newLastName)}>
- change last name
- </button>
- </h1>
- );
- }
- App.mapState = (state, props) => {
- return { name: state.name };
- }
- App.mapDispatch = (dispatch, props) => {
- return {
- handleClick: (name) => () =>
- dispatch({ type: 'UPDATE', name }),
- };
- }
- // class App extends Component {
- // static mapState(state, props) {
- // return { name: state.name };
- // }
- // static mapDispatch(dispatch, props) {
- // return {
- // handleClick: (name) => () =>
- // dispatch({ type: 'UPDATE', name }),
- // };
- // }
- // render() {
- // return (
- // <h1
- // onClick={this.props.handleClick(
- // this.props.name.split('').reverse().join('')
- // )}
- // >
- // <Test /> {this.props.name}
- // </h1>
- // );
- // }
- // }
- function container(WrappedComponent) {
- const mapState = WrappedComponent.mapState || null;
- const mapDispatch = WrappedComponent.mapDispatch || null;
- return connect(mapState, mapDispatch)(WrappedComponent);
- }
- const AppContainer = withState({
- lastName: 'Xalambrí',
- })(container(App));
- function reducer(state, action) {
- if (action.type === 'UPDATE') {
- return { name: action.name }
- }
- return state;
- }
- const store = createStore(reducer, { name: 'Sergio' });
- render(
- <Provider store={store}>
- <AppContainer />
- </Provider>,
- document.body
- );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement