Reactjs
Tips and best practices
Barcamp Shanghai 2018/06/08
Luciano Wu
- Started developing with react-native in 2015
- Full stack developer
- 2017 ~ CTO at Edugora
About me
Edugora stack
React Components
// component definition
class Button extends React.Component {
render() {
const { title } = this.props;
return (
<div style={...}>
{title}
</div>
);
}
}
// component usage
<Button title={"Login"} />
React Components
// component definition
class Button extends React.Component {
_doLogin = () => {
...
}
render() {
const { title, onClick } = this.props;
return (
<div
style={...}
onClick={this._doLogin}
>
{title}
</div>
);
}
}
// component usage
<Button title={"Login"} />
// component definition
class Button extends React.Component {
render() {
const { title } = this.props;
return (
<div
style={...}
onClick={onClick}
>
{title}
</div>
);
}
}
// component usage
const doLogin = () => {
...
}
<Button title={"Login"} onClick={doLogin} />
Too many components!?
react-components-docs
Automatic visual documentation for components
files
webpage
export default class Button extends Component {
static propExamples = [{
props: {
title: "Button",
backgroundColor: "#00A3FF",
},
description: "Primary"
}, {
props: {
title: "Button",
backgroundColor: "#6DCC50",
},
description: "Secondary"
}, {
props: {
title: "Button",
backgroundColor: "#ec1c24",
},
description: "Danger"
}]
render() {
const { title, backgroundColor } = this.props;
return (
<div style={{...styles.container,backgroundColor}}>
{title}
</div>
);
}
}
State management
redux
redux
redux-logic
redux-thunk
redux-observables
redux-saga
dvajs
mobx
A lot of ways to manage your state
- Too much boilerplate
- redux with typescript. How to add types to the dispatch function?
issues with redux
dispatch({
type: "increment",
payload: {
count: 1
}
})
- reducer
- action types
- action creators
eduxo
const initialState = {
isLoading: false,
};
const model: IModel<IState, IDispatchers> = {
namespace: 'home',
initialState,
reducers: {
[actionTypes.showLoading]: (state = initialState, action) => {
return {
isLoading: true,
};
},
[actionTypes.hideLoading]: (state = initialState, action) => {
return {
isLoading: false,
};
},
},
generateDispatchers: dispatch => {
return {
showLoading: () => {
dispatch({
type: actionTypes.showLoading,
});
},
};
},
};
const app = new Eduxo<IDispatchers>(initialDispatchers, middleware);
app.require(model)
app.init();
app.getState().home.isLoading // false
app.dispatchers.home.showLoading();
app.getState().home.isLoading // true
https://github.com/han4wluc/react-component-docs
eduxo still in under development
Reactjs tips and best practices
By Luciano Hanyon Wu
Reactjs tips and best practices
- 380