Recently, Redux + react seems to be getting more and more popular in the front-end circle. However, even the official documents only give oneTodomvc example, hundreds of lines of code and too many new concepts are still very complex for many beginners (including me).
Google Baidu has searched, but has not found a simple fool. It is like the quick start of Hello world, so I spent a little time today to write the simplest demo (really the simplest / w \):
Github:https://github.com/starkwang/react-redux-es6-quickstart
1、 Construction of development environment
1、webpack
First of all, we need the packaging tool webpack (ignore it if you already have it):
sudo npm install -g webpack
2. Dependent package
Create a folder by any name, such asredux-test
。
mkdir redux-test && cd redux-test
Then install the following dependent packages with NPM:
-
babel-loader
-
react
-
react-dom
-
react-redux
-
redux
3. Configuration file for webpack
In this project, ES6 and JSX need to be converted into Es5 syntax that can be run by the browser, so we need to use webpack and its Babel loader for conversion and packaging. Here we defaultindex.jsx
It’s an entry file.
//webpack.config.js
module.exports = {
entry: 'index.jsx',
output: {
filename: 'bundle.js'
},
module: {
loaders: [{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel', // 'babel-loader' is also a legal name to reference
query: {
presets: ['es2015','react']
}
}]
}
};
Take thiswebpack.config.js
Just put it in the directory.
4、HTML
First, we need an HTML page with an ID ofroot
ofdiv
As the root node of our application:
<!DOCTYPE html>
<html>
<head>
<title>React-Redux Hello World</title>
</head>
<body>
<div id="root"></div>
</body>
<script type="text/javascript"></script>
</html>
2、 Start writing code
There are too many introductory courses of online react, so I won’t repeat them.
Please be sure to finish reading about reduxChinese documentsIntroduction to.
Now we mainly want to realize the effect in Demo:
Click here to see demo
1. When clicking the text, the text will switch back and forth in “hello” and “stark”;
2. When you click the button, the text will change to “you just click button”.
The following code is in the same file index JSX!
The following code is in the same file index JSX!
The following code is in the same file index JSX!
0. Import dependent packages
We need the ontology of react and the ontology of react domrender
Method, ReduxcreateStore
andbindActionCreators
Method and react reduxProvider
andconnect
method
import React from 'react';
import { render } from 'react-dom';
import { createStore,bindActionCreators } from 'redux';
import { Provider ,connect } from 'react-redux';
1、Action
Obviously, we need to define two kinds of events: “text switching back and forth” and “button clicking”.
//action
//We don't use const to declare constants here. It's not recommended to do this in actual production
function changeText(){
return {
type:'CHANGE_TEXT'
}
}
function buttonClick(){
return {
type:'BUTTON_CLICK'
}
}
2、Reducer
For different actions, the corresponding state transitions are also different:
//reducer
//The initial state is "hello"
const initialState = {
text: 'Hello'
}
function myApp(state = initialState, action) {
switch (action.type) {
case 'CHANGE_TEXT':
return {
text:state.text=='Hello'?'Stark':'Hello'
}
case 'BUTTON_CLICK':
return {
text: 'You just click button'
}
default:
return {
text:'Hello'
}
}
}
3、Store
Store is directly generated by Redux:
let store = createStore(myApp);
4. Components
There are three components: text componentHello
, buttonChange
, and their parent componentsApp
//Hello
class Hello extends React.Component{
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick(){
this.props.actions.changeText();
}
render() {
return (
<h1 onClick={this.handleClick}> {this.props.text} </h1>
);
}
}
//Change
class Change extends React.Component{
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick(){
this.props.actions.buttonClick();
}
render() {
return (
<button onClick={this.handleClick} >change</button>
);
}
}
//App
class App extends React.Component{
constructor(props) {
super(props);
}
render() {
//Actions and text props will be explained in step 5
const { actions, text} = this.props;
return (
<div>
<Hello actions={actions} text={text}/>
<Change actions={actions}/>
</div>
);
}
}
5. Connect react components and Redux
//Mapstatetoprops is used to declare which attributes we care about when the state tree changes?
//Because our application is too small and has only one attribute, we only have the field text.
function mapStateToProps(state) {
return { text: state.text }
}
//Mapdispatchtoprops is used to inject the dispatch method in the store into the component
function mapDispatchToProps(dispatch){
return{
actions : bindActionCreators({changeText:changeText,buttonClick:buttonClick},dispatch)
}
}
//The app is actually given two props: text and actions, that is, the comment in step 4
App = connect(mapStateToProps,mapDispatchToProps)(App)
6. Render our app
//Provider is directly provided by react redux
//The store is generated in step 3
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)
7. Compilation and packaging
Remember the installed webpack and the written configuration file?
Execute directly under the project directory:
webpack
Then you canindex.jsx
Compile and package intobundle.js
Yes
3、 Index JSX source code
Here is index The complete source code of JSX can be copied directly
import React from 'react';
import {render} from 'react-dom';
import { createStore,bindActionCreators } from 'redux';
import { Provider ,connect} from 'react-redux';
//action
function changeText(){
return {
type:'CHANGE_TEXT'
}
}
function buttonClick(){
return {
type:'BUTTON_CLICK'
}
}
//reducer
const initialState = {
text: 'Hello'
}
function myApp(state = initialState, action) {
switch (action.type) {
case 'CHANGE_TEXT':
return {
text:state.text=='Hello'?'Stark':'Hello'
}
case 'BUTTON_CLICK':
return {
text: 'You just click button'
}
default:
return {
text:'Hello'
};
}
}
//store
let store = createStore(myApp);
class Hello extends React.Component{
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick(){
this.props.actions.changeText();
}
render() {
return (
<h1 onClick={this.handleClick}> {this.props.text} </h1>
);
}
}
class Change extends React.Component{
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick(){
this.props.actions.buttonClick();
}
render() {
return (
<button onClick={this.handleClick} >change</button>
);
}
}
class App extends React.Component{
constructor(props) {
super(props);
}
render() {
const { actions, text} = this.props;
return (
<div>
<Hello actions={actions} text={text}/>
<Change actions={actions}/>
</div>
);
}
}
function mapStateToProps(state) {
return { text: state.text }
}
function mapDispatchToProps(dispatch){
return{
actions : bindActionCreators({changeText:changeText,buttonClick:buttonClick},dispatch)
}
}
App = connect(mapStateToProps,mapDispatchToProps)(App)
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)
4、 Summary
If you can still live to see it here, you must be roast, “how can you write 100+ lines of code for a simple toy like a sleeping trough that even jQuery doesn’t bother to use?”
Yes, as a variant of the flux architecture, Redux is originally “suitable for large-scale applications”. It solves the problem of chaotic data flow when the application complexity increases, rather than directly improving your code efficiency.
Sometimes, using angular, jQuery or even native JS for a few lines of code is divided into action, reducer and store under redux. Although inefficient, the complexity of the project can be well managed when the project is getting larger and larger.