Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to build a react project

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces how to build a react project related knowledge, the content is detailed and easy to understand, the operation is simple and fast, has a certain reference value, I believe you will gain something after reading this article on how to build a react project, let's take a look at it.

1. Npm init generates package.json files.

2. Install various required dependencies:

Npm install

-- save react-install React.

Npm install

-- save react-dom installs React Dom, which is used to handle virtual DOM. If you mention using React Native here, this is where you install react-native.

Npm install

-- save-dev webpack-install Webpack, now the most popular module packaging tool.

Npm install

Save-dev webpack-dev-server-webpack official website of a small express server, the main feature is to support hot loading.

Npm install

-- save-dev babel-core-install Babel to convert ES6 to ES5. Note that the latest V6 version of Babel is divided into two modules: babel-cli and babel-core. You only need to use babel-cor here.

Install other babel dependencies (babel is really a family bucket, go to the official website for details. I'll sum it up later, it's all installed here anyway):

Npm install

Save babel-polyfill-Babel includes a polyfill that includes a custom regenerator runtime and core.js. This will emulate a full ES6 environment

Npm install

-- loader needed in save-dev babel-loader-webpack.

Npm install

-- save babel-runtime-Babel transform runtime plug-in dependency.

Npm install

Save-dev babel-plugin-transform-runtime-Externalise references to helpers and builtins, automatically polyfilling your code without polluting globals.

Npm install

Save-dev babel-preset-es2015-Babel preset for all es2015 plugins.

Npm install

Save-dev babel-preset-react-Strip flow types and transform JSX into createElement calls.

Npm install

Save-dev babel-preset-stage-2-All you need to use stage 2 (and greater) plugins (experimental javascript).

3. Open package.json and add the following scripts:

"scripts": {"start": "webpack-dev-server-hot-- inline-- colors-- content-base. / build", "build": "webpack--progress-- colors"}

Enter npm start on the command line to start webpack dev server.

Typing npm build on the command line will package the production environment.

4. Start webpack

Webpack is our packaging tool, which plays a very important role in our development environment. It has many convenient features, especially hot-loaded hot reloading. Webpack.config.js is the configuration file for webpack as shown below. With the continuous change of app, the configuration file will be constantly updated. Here we will name the configuration file with the default webpack.config.js. If you use another name, such as webpack.config.prod.js, then the above script build needs to change and specify the corresponding configuration file name: "build": "webpack webpack.config.prod.js-- progress-- colors".

Var webpack = require ('webpack') Module.exports = {entry:'. / src/app.js', output: {path: _ _ dirname +'/ build', filename: "bundle.js"}, module: {rules: [{test: /\ .js $/, exclude: / node_modules/, loader: 'babel-loader', query: {plugins: [' transform-runtime'], presets: ['es2015',' react'] 'stage-2']}, {test: /\ .css $/, loader: "styleMutual loader loading CSSS loader"}}

OK, the basic configuration of our project is finally complete, and it's time to start writing Reac code.

React Foundation-build your first Component

Based on the basic configuration of the above project, we began to write the first component of React to familiarize ourselves with the writing and component thinking of React.

First, we create a new index.html file in the root of the project. In this basic project, we use the style of bootstrap and directly introduce a cdn. Then add a html tag and our app will be injected into the div. Finally, this is the final package of the generated js code.

Here is the complete code:

Document

Create a new folder src. Most of our app code will be in this folder. Set up app.js in src, and as the root component of React App, all other components will be injected into this and component.

First we need to import react, now we all use the syntax of ES6, import React from 'react';, and then we need to introduce react-dom. There is the most important concept of virtual dom in react. Introduction Code: import ReactDOM

From 'react-dom'

Now that the dependencies that need to be introduced are over, we can write the first component:

Class App extends React.Component {render () {/ / Every react component has a render method. Return (/ / Every render method returns jsx. Jsx looks like HTML, but it's actually javascript and functions a lot like xml, with self closing tags requiring the `/ `within the tag in order to work propperly Hello World);}}

Notice that the word "Hello World" is written in div here. All jsx code needs to be written in a parent div.

Finally, we need to give our written component render to Dom, and here we need to use the ReactDOM.render method.

Add: ReactDOM.render (, document.getElementById ('app')) under App.js

The first parameter is the root component of our App, the form of writing. The second parameter is the main DOM element that our APP will have. In this project, it is the div tag that we wrote in index that id is app.

Ok, our APP structure has come out, and the classic hello world has been implemented. Right now, we will implement the classic todo app on this basis. The rough prototype has an input box for entering to-do items and adding them to the event list. Each to-do item in the event list will be marked with a delete line to indicate completion, and it will be deleted from the list by clicking the delete button below. By completing this APP process you will learn all the basic building blocks of a complete react app.

Lifecycle approach and two forms of component construction

We start with some small modules. A component component is a building block of react app. There are two forms of components: Class and Functional. In this project, we will use both forms of components and use lifecycle hooks, as well as two important properties in the react, state and props.

First create a new components folder in the src folder, and your file structure is like this ~ / src/components.

Then create a new file ToDoApp.js in components. For all react components, we need to introduce reactimport React from 'react'; in the header.

Let's write a class component. All class components have a render method to return jsx.

The class for ToDoApp is as follows:

Class ToDoApp extends React.Component {render () {return (ToDoApp);}}

To inject this component into our APP, we first need to output it. Add export default ToDoApp; at the bottom of the component code.

Then at the top of the app.js we add the import ToDoApp from '.components / ToDoApp'; import component to replace the Hello World. Replace it with the new jsx code semi-closed type tag in render.

Then in the browser you can see that "To Do App" has replaced the original "Hello World"! This completes embedding the first subcomponent into the root component, which is the general pattern for building react app. Let's continue to refine our components.

Go back to ToDoApp to build our first to-do list. First of all, we use bootstrap to build more convenient and beautiful. Replace the jsx in return in the current render method with the following jsx:

My To Do App List goes here.

Now open the browser and you will see a panel component with the title "My To Do App" followed by a bootstrap with "List Goes Here" written in it, where we will build the list. So how do we store the data in our list? The answer is to use state. Each class component has a state attribute, which can be obtained anywhere in the component through this.state and with this.setState ({

Key: "value"}) this is the way to update the status. But unless we need to use state less, we will use it as an understanding for the time being, and we will use redux to manage state later.

There are many hooks for lifecycle methods that we can use in ToDoApp, one of which is componentWillMount. This method is executed before the page loads and before the render method. You can get the list data in it and provide it directly in a virtual array in our APP. It is worth noting that componentWillMount can cause a lot of minor problems, so try not to use it in real projects, but instead use componentDidMount.

Add before the render method in ToDoApp:

ComponentWillMount () {/ / run before the render method this.setState ({/ / add an array of strings to state. List: ['thing1',' thing2', 'thing3']})}

Now that we've got a virtual list, it's important to note that react depends on state and props, and react components refresh only when state and props change.

Now we add the list to the view, instead of simply modifying the jsx in it, we create a new component to build the list. This time we learn to use functional components. It is important to note that functional components have no lifecycle methods and state properties, it is just a function that returns jsx, and the argument is props.

So what exactly is props? Props is the name of the data passed into the child component from the parent component, which is an important concept and the most typical and recommended method of react app data transfer. Usually we keep the data on the top component of the app and let the data flow down through the component to ensure the accurate operation of the APP. This data and some processing of props may affect the operation of APP, but if you follow the practical process of this course, these effects will be very small.

Create a new components folder and create a new List.js in it as the functional component we want to create. Create a new function with const, and write the parameter name as props.

The function forms are as follows:

Const List = (props) = > {/ / we're using an arrow function and const variable type, an ES6 features return (I am a listener!)}; export default List

List is introduced into ToDoApp.js to replace List goes here., with List components. Now you can see "Isima listeners!" in the browser.

Now let's turn this into a real list, first of all, we need to pass the data through props, and we pass the data from state list through a props named listItems, written: now List has obtained the data in ToDoApp through props.

Then we need to render a list in the List component, replacing it with the following jsx code:

{list / / this is a variable we'll define next}

Notice the curly braces, where js can execute and add the return to the view. First, let's define a list variable:

Const list = props.listItems.map ((el, I) = > (/ / All where doing here is getting the items listItems prop / / (which is stored in the state of the parent component) / / which is an array, and we're running the .map method / / which returns a new array of list items. The key attribute is / / required, and must be unique. El))

The complete components are as follows:

Import React from 'react';const List = (props) = > {const list = props.listItems.map ((el, I) = > (el)); return ({list})}; export default List

Now open the browser and you can see a list. The next step is to add functionality to our project, including adding new items, tagging items to complete, and deleting items from the list.

Add functions to APP

1. Functional component

First we need to add an input element so that we can enter the to-do items. So we create a new Input.js in the components folder, and then create and output a functional component called Input in it.

Paste the following jsx code into your functional component return:

Email address Add Item

2. Input

Now our jsx doesn't do anything special, just a basic html view, but let's test it and import it into ToDoApp.js in the form.

At this point, you will find a view of the input box and buttons. The static view of this component has been written, so you need to add functions.

3. Props

The first thing we need to do is how to get the value of the input box, because the value of this input box needs to be obtained in other components, so we do not want to deal with this data store in the Input component. In fact, storing data in subcomponents is not recommended at any time, and we should store the data in the top component of app and pass it down through props.

Another thing to keep in mind is that even though we currently store the data in the upper ToDoApp components, we will later use redux instead of processing the entire app data. Here we just use react's state to implement it.

Ok, we added a newToDo attribute to the setState of the componentWillMount of ToDoApp to store the value of the input box.

ComponentWillMount () {this.setState ({list: ['thing1',' thing2', 'thing3'], newToDo:' test'})}

The same can be passed on through props.

4. Deconstruction (Destructuring)

In Input.js, we can get the value passed by the parent component through the parameter props, but it can also be deconstructed with the new features of ES6 as a parameter, which looks even cooler!

Change the props parameter of the Input component to ({

Value}), so that the object parameter props can be deconstructed into key-value pairs. Just look at a small example to make it clear:

Var props = {name: 'hector', age: 21} function log (props) {console.log (props.name); console.log (props.age);} log (props)

Is the same as this:

Let props = {name: 'hector', age: 21} log = ({name, age}) = > {console.log (name); console.log (age);} log (props)

5. SetState

The above newToDo just adds a state to store the value of the input box, given a value, the input box will be displayed, obviously not the effect we want, what we need to do is to dynamically change the state based on the value of the input box.

To achieve this, we need to add another onChange method that also uses props to pass in the Input component: onChange= {onChange}, and then the deconstruction parameter is ({onChange, value}).

Then add a new method, onInputChange, to ToDoApp.js 's componentWillMount. This method has a parameter event, which will capture the value entered by the user in the input box.

OnInputChange = (event) = > {this.setState ({newToDo: event.target.value}) / / updates state to new value when user changes the input value}

6. Add a new list item

Now you need to add a new item to the list, that is, the value of the input box can be stored and displayed in the list after submission. We need to create a new onInputSubmit method, the parameter is also event, the function body first needs to write event.preventDefault (), and then use the setState method to add new items to the list array, but we must note that our state should be immutable, which is a criterion that must be followed in react in order to ensure comparison and reliability.

To achieve this function, you need to use the this.setState callback function with an argument of previousState:

This.setState ((previousState) = > ({list: previousState.list.push (previousState.newToDo)}))

As I described above, many people will make such mistakes at the beginning of writing state, directly using the method of push to modify the state, so it is not immutable, we must make sure that we will never directly modify the original state.

Here we can use the new feature in ES6, the extension operator, which returns a new array by traversing the old array, leaving the old array as it is, so we add items to the end of the list array:

This.setState ((previousState) = > ({list: [... previousState.list, previousState.newToDo], / / the spread opperator is called by using the... Preceding the array}))

When submitting the new item, you need to reset the newToDo to'':

This.setState ((previousState) = > ({list: [... previousState.list, previousState.newToDo], newToDo:''}))

7. Cross out items

It's time to add the ability to cross out items. In order to achieve this function, you need to add a new attribute to mark whether it needs to be crossed out, so you need to change the original array to an object array, each item is an object, a key represents the original item content for item, and a key for done uses a Boolean value to indicate whether or not to cross out. Then modify the original onInputSubmit method first, and also pay attention to immutable, using the extension operator as follows:

OnInputSubmit = (event) = > {event.preventDefault (); this.setState ((previousState) = > ({list: [... previousState.list, {item: previousState.newToDo, done: false}], / / notice the change here newToDo:''});}

After the property done is added, you need to add a new method to change this value when you click on the item:

OnListItemClick = (I) = > {/ / takes the index of the element to be updated this.setState ((previousState) = > ({list: [... previousState.list.slice (0, I), / / slice returns a new array without modifying the existing array. Takes everything up to, but not including, the index passed in. Object.assign ({}, previousState.list [I], {done:! previousState.list [I] .done}), / / Object.assign is a new ES6 feature that creates a new object based on the first param (in this case an empty object). Other objects can be passed in and will be added to the first object without being modified. .. previousState.list.slice (iTun1) / / takes everything after the index passed in and adds it to the array. ]})}

This method is then passed to the List component via props, so there is no use of deconstruction parameter passing, which is used for comparison with Input's. Because this function needs an argument that is the sequence number of the current list, but you can't call this function directly or you will get an error. Therefore, use the bind method to enter and exit the I parameter:

OnClick= {props.onClick.bind (null, I)}

Of course, there is another way:

OnClick= {() = > props.onClick (I)}

Then add the onClick method to the span tag of the item content, change the done value of the current item, and then modify the style by judging the Boolean value or cross out the delete line.

8. Delete item

Finally, we are adding the function of deleting items, which is very similar to crossing out items. We only need to add a delete button and then add a list of method modifications, as shown in the following code:

XdeleteListItem = (I) = > {this.setState ((previousState) = > ({/ / using previous state again list: [... previousState.list.slice (0, I), / / again with the slice method... previousState.list.slice (iTun1) / / the only diffence here is we're leaving out the clicked element]}))}

Pass the deleteListItem method to the list component and bind it to the delete button, just follow the example of the previous one and write it yourself.

Now that we have a fully functional APP, does it feel very cool? this is the form without redux, but you will find that it is very tedious when the state is becoming more and more complex, so we are going to introduce redux to manage the state.

Preparations for migrating to redux

So far we have learned how to use webpack and babel to build react applications, build class components and functional components, deal with state, and add functions. However, this only basically meets the needs of a small application, with the growth of app, it will be more and more difficult to deal with data and behavior, which is the necessity of introducing redux.

So how does redux handle the data? First of all, redux gives your app a single state object, which is the opposite of how flux and others are divided into multiple state objects according to view. You may wonder, isn't it very complicated for a single object to deal with a complex app? The method adopted by redux is to divide the data processing into reducer functions, action creators and actions and then work together to process the data in a streamlined manner.

1. First install the necessary dependencies

Install redux and react-redux first

Npm install-save reduxnpm install-save react-redux

Then install redux middleware, here first install redux-logger, its function is to help us develop.

Npm install-save redux-logger

There are also some commonly used middleware, such as redux-thunk and redux-promise, but we don't need it for the time being in this project. We can go to github to learn about it.

two。 Construction

There is generally a standard template for building react applications using redux, which may be different in form, but the idea is the same, so let's first build it according to a file structure.

First, let's create a new folder redux in src, then create a new file configureStore.js in it, and add the following code:

Import {createStore, applyMiddleware, combineReducers} from 'redux';import createLogger from' redux-logger'

CreateStore is a function provided by redux to initialize store, and applyMiddleware is used to add the middleware we need.

CombineReducers is used to merge multiple reducers into a single entity.

CreateLogger is the only middleware we use here, which can console the detailed data processing process after each action, which brings great convenience to debugging.

Then add the following code:

Const loggerMiddleware = createLogger (); / / initialize loggerconst createStoreWithMiddleware = applyMiddleware (loggerMiddleware) (createStore); / / apply logger to redux

It is not finished here for the time being. We need to finish the later module and then import it here to continue to complete.

3. Module Modules

Create a new folder modules in src/redux/. We will store all the reducers,action creators and constants in this folder. Here we use the redux organizational structure called ducks, the idea is to put the relevant reducers,action creators and constants in a separate file, rather than separate in multiple files, so that you can modify a function directly in a file.

Create a new 'toDoApp.js', in the modules file. Note that the naming here is based on the name of the container component, which is also the specification and is easy to manage the code.

Now we can start to create initial state and reducer function, which is actually very simple. State is a js object, and reducer is the switch statement of js:

Const initialState = {}; / / The initial state of this reducer (will be combined with the states of other reducers as your app grows) export default function reducer (state = initialState, action) {/ / a function that has two parameters, state (which is initialized as our initialState obj), and action, which we'll cover soon. Switch (action.type) {default: return state;}}

4. Perfect Store

Now that we have completed the first reducer, we can add it to the configureStore.js and import: import toDoApp from'. / modules/toDoApp'

Then use combineReducers to combine the current reducer, as more modules will be added in the future.

Const reducer = combineReducers ({toDoApp})

Finally, add the following complete code at the bottom:

Const configureStore = (initialState) = > createStoreWithMiddleware (reducer, initialState); export default configureStore;Cool. We're done here.

5. Connect

Now that we have a reducer, how do we get in touch with app? It takes two steps to work.

We have already talked about class components and functional components, sometimes called smart components and dumb components, here we add a container component, as the name implies, this component is used as a container to provide actions and state to the component.

To create the first container component, first add a folder containers under / src/, and then create a new text toDoAppContainer.js under it.

Import connect at the top of the file first to link containers and components together

Import {connect} from 'react-redux';import ToDoApp from'.. / components/ToDoApp.js'

The function connect is called twice, the first being two callback functions: mapStateToProps and mapDispatchToProps. The second time is when you pass state and dispatch into the component. What is the dispatch here?

When we need to do something in redux, we need to call the dispatch function to pass an action and then call the reducer process. Because we haven't written a specific behavior yet, we'll just leave it blank here and fill it later. The code looks like this:

Function mapStateToProps (state) {return {toDoApp: state.toDoApp / / gives our component access to state through props.toDoApp}} function mapDispatchToProps (dispatch) {return {}; / here we'll soon be mapping actions to props}

Then add at the bottom:

Export default connect (mapStateToProps, mapDispatchToProps) (ToDoApp)

1 、 Provider

The basic work of redux has been completed. The last step is to return to the app.js file. First, we no longer need to import the ToDoApp component, but replace it with the container component ToDoAppContainer. Then we need to import the configureStore function and Provider, and add code in the header:

Import {Provider} from 'react-redux';import ToDoAppContainer from'. / containers/ToDoAppContainer';import configureStore from'. / redux/configureStore'

ConfigureStore is the function we created that takes our combined reducers and our redux middleware and mashes them all together. Let's intialize that with the following line:

Const store = configureStore ()

Then in the jsx of return, you also need to change ToDoApp to ToDoAppContainer, and then you need to wrap it with a Provider component, and its function is to pass the state of the entire app to the container it wraps, so that the container component can obtain these state.

/ / we pass the store through to Provider with props

Now that the basic structure of the entire redux has been built, the next step is to add the entire behavior logic code.

Redux Actions and Reducers

After setting up the basic structure of redux, we can populate the elements of redux. To put it simply, we only need to remember four concepts, Types, Actions, Action Creators, and and Reducers. Then organize these elements with the file organization structure of ducks.

Ducks

Rules

In module, we need to follow the following code style and naming:

You need to use export default to output a function named reducer ()

Action creators in the form of export output function is required

It is necessary to use the naming form of npm-module-or-app/reducer/ACTION_TYPE to name action types, because in the later stage of many reducer, different people will inevitably have repeated naming when they work together, so that if you add the prefix of app and module, there will be no naming conflict.

The action types must be named with an uppercase serpentine UPPER_SNAKE_CASE.

Types

This types is the constant name that needs to be named according to the specification of ducks in the third above. Write it at the top of the file. When action triggers, the switch statement that will be passed to reducer,reducer will process the data according to this type.

Const ADD_ITEM = 'my-app/toDoApp/ADD_ITEM';const DELETE_ITEM =' my-app/toDoApp/DELETE_ITEM'

Actions

An Actions is a simple js object that contains at least type and can also contain data for passing to reducer. When a user triggers a behavior on the page, an aciton creator will send aciton to reducer for data processing.

An example of action is as follows:

{type: ADD_ITEM, item: 'Adding this item'} {type: DELETE_ITEM, index: 1} {type: POP_ITEM}

Action Creators

Action creators is a function that creates acitons and passes it to reducer. It usually returns an action object, and sometimes middleware such as thunk can also return multiple actions of dispatch, which is not involved in our app for simplicity.

Function addItem (item) {return {type: ADD_ITEM, item / / this is new ES6 shorthand for when the key is the same as a variable or perameter within the scope of the object. It's the same as item: item}}

Reducers

Reducer is the only element that can touch store, with an initial value of initialState, which is formally a simple switch statement, but note that you can't change state directly, because state is immutable. That is, we cannot directly use .pop or. Push these methods to manipulate arrays.

Here is the sample code:

Const initialState = {list: []}; export default function reducer (state = initialState, action) {switch (action.type) {case ADD_ITEM: return Object.assign ({}, state, {list: [... state.list, action.item]} / / here we see object.assign again, and we're returning a new state built from the old state without directly manipulating it) default: return state;}}

Now that the concept has been introduced, let's rewrite the original functional logic in redux.

1. Initial state

First we declare initialState in src/redux/modules/toDoApp.

Const initialState = {list: [{item: 'test', done: false}] / / just added this to test that state is being passed down propperly, newToDo:''}; export default function reducer (state = initialState, action) {switch (action.type) {default: return state;}}

Now adding console.log (this.props) before return in the render () method of ToDoApp.js prints out the following object:

ToDoApp: Object list: Array [1] 0: "test" length: 1 _ _ proto__: Array [0] _ proto__: Object__proto__: Object

After the test passes, we can pass this data to the subcomponents, and here we can replace the listItems prop of the original List component and the value prop of Input.

The data has just been replaced here, and the action needs to be replaced as well.

3. Input action

This process is to migrate all the behavior logic of our original ToDoApp components to the toDoApp module under the redux folder.

Const INPUT_CHANGED = 'INPUT_CHANGED';export function inputChange (newToDo) {return {type: INPUT_CHANGED, newToDo}}

Then add the following processing to the switch of reducer:

Case INPUT_CHANGED: return Object.assign ({}, state, {newToDo: action.value})

The mapDispatchToProps function in toDoAppContainer.js needs to return the corresponding action. Import inputChange first, as shown in the following code:

Import {connect} from 'react-redux';import ToDoApp from'.. / components/ToDoApp.js'import {inputChange} from'. / redux/modules/toDoApp'; / / we added thisfunction mapStateToProps (state) {return {toDoApp: state.toDoApp / / gives our component access to state through props.toDoApp}} function mapDispatchToProps (dispatch) {return {inputChange: (value) = > dispatch (inputChange (value)) / / we added this};} export default connect (mapStateToProps, mapDispatchToProps) (ToDoApp)

In this way, both state and action are passed to toDoApp and then passed to sub-components through props, depending on the final code of the project.

4. Other actions

The other acitons code patterns are basically the same as above, and I won't repeat them here.

This is the end of the article on "how to build a react project". Thank you for reading! I believe you all have a certain understanding of "how to build a react project". If you want to learn more, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report