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

What errors will be encountered in developing with React Native/Redux

2025-03-13 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly shows you "what mistakes will be encountered in the development of React Native/Redux", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "what mistakes will be encountered in the development of React Native/Redux" this article.

1. A false estimate.

It is possible that your estimate of * React Native (RN) applications is completely wrong!

1) you need to consider the layout of iOS and Android versions respectively! There are many components that can be reused when laying out; if ios and Android have different page structures, they need to be laid out separately.

2) when evaluating form, * also consider data layer verification.

3) understanding the database structure is helpful to correctly plan redux.

two。 Use basic components (buttons,footers,headers,inputs,texts) as much as possible

Google searches the basic components of RN and you will find that there are many existing components that can be easily used in the project, such as buttons,footers and so on. If there is no special layout design in the project, you only need to use these basic components to build a page. If you have some special design, such as a special button style, you need to set a custom style for each button. You can encapsulate components that have already been built and customize styles for them. But I think it makes more sense to build your own components using View,Text,TouchableOpacity and other components of RN. Because you will have more rn practices and a deep understanding of how to use RN. Most importantly, you can make sure that the version of the component you build will not be changed.

3. Do not separate the layout of iOS and Android

If the iOS and Android layouts are roughly the same, with only a few differences, you can simply use the Platform API provided by RN to distinguish according to the device platform.

If the layout is completely different-separate layouts are scattered in different files.

If you name a file index.ios.js-when the program is packaged, this file will be used in iOS to display the iOS layout. The same goes for index.android.js.

You might ask, "how is the code reused?" You can move the duplicate code to the helper function. Only these helper functions are reused when needed.

4. Wrong redux store planning.

A big mistake that beginners often make is that when you are planning your application, you may consider a lot of layout-related issues, but little about data processing.

Redux can help us store data correctly. If redux is well planned-it will be a powerful tool for managing application data.

When I first started building RN applications, I considered reducers as a data store for each container. So, if you have login, forget your password, to-do list page-it's easier to use their abbreviations: SignIn, Forgot, ToDoList.

After a period of work, I found that managing data was not as easy as I thought.

When I select an item from the ToDo list-I need to pass the data to ToDoDetails reducer. This means that additional operations are used to send data to reducer.

After doing some research, I decided to plan the structure in a different way. An example:

Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community

Auth

Todos

Friends

Auth is used to store the token for authentication.

While ToDos and Friends reducers are used to store entities, when I go to the ToDo Detail page-I just need to search all the ToDos through ID.

For more complex structures, I recommend using this kind of planning, where you can quickly locate what you want to find.

5. Wrong project structure

As a beginner, it is always difficult to plan the project structure.

First of all, you need to analyze whether your project is big enough.

How many pages are there in your application? 20'30'10'5? Or is there only one "Hello World" page?

The structures I encountered and began to implement are as follows:

If your project has no more than 10 pages, there is no problem with using the above structure. But if the project is very large-you can consider this planning structure:

The difference is that actions and reducers are recommended to be stored separately from container. The second kind-store them together. If the application is small-it is more useful to separate the redux module from the container.

If you have common styles (such as Header, Footer, Buttons)-you can simply create a folder called "styles", where you can set up an index.js file and write general styles in it. Then reuse them on each page.

There will be many different structures in the actual project. You should know which structure suits your needs better.

6. Wrong container structure. Did not use smart/dumb components from the beginning

When you start using RN and initialize the project, there is already some code in the index.ios.js file that is stored in a separate object.

In an actual development project, you will need to use a lot of components, not only provided by RN, but also some of the components you build yourself. When building container, you can reuse them.

Consider this component:

Import React, {Component} from 'react'; import {Text, TextInput, View, TouchableOpacity} from' react-native'; import styles from'. / styles.ios'; export default class SomeContainer extends Component {constructor (props) {super (props) This.state = {username:null}} _ usernameChanged (event) {this.setState ({username:event.nativeEvent.text});} _ submit () {if (this.state.username) {console.log (`Hello, ${this.state.username}! `) } else {console.log ('Please, enter username') }} render () {return (Username) Submit) }}

All styles are stored in a separate module.

Button components wrapped in TouchableOpacity should be separated separately so that we can reuse it later. The Image component may also be reused in the future, so it should also be separated.

What it looks like after making some changes:

Import React, {Component, PropTypes} from 'react'; import {Text, TextInput, View, TouchableOpacity} from' react-native'; import styles from'. / styles.ios'; class Avatar extends Component {constructor (props) {super (props) } render () {if (this.props.imgSrc) {return ()} return null }} Avatar.propTypes = {imgSrc: PropTypes.object} class FormItem extends Component {constructor (props) {super (props);} render () {let title = this.props.title Return ({title})} FormItem.propTypes = {title: PropTypes.string, value: PropTypes.string, onChange: PropTypes.func.isRequired} class Button extends Component {constructor (props) {super (props) } render () {let title = this.props.title Return ({title})}} Button.propTypes = {title: PropTypes.string OnPress: PropTypes.func.isRequired} export default class SomeContainer extends Component {constructor (props) {super (props) This.state = {username:null}} _ usernameChanged (event) {this.setState ({username:event.nativeEvent.text});} _ submit () {if (this.state.username) {console.log (`Hello, ${this.state.username}! `) } else {console.log ('Please, enter username');}} render () {return () }}

Now the code looks more-because we added wrappers to the Avatar,FormItem and Button components, but now we can reuse them where needed. We can move these components into separate modules and import them wherever we need them. We can also add some other Props, such as style,TextStyle,onLongPress,onBlur,onFocus. And these components are completely customizable.

Be careful not to deeply customize a widget, which will make the component too cumbersome and the code difficult to read. Even if the idea of adding a new attribute now seems like the easiest way to solve the task, this small attribute may cause confusion when reading the code in the future.

For the ideal smart/dumb component, take a look at this:

Class Button extends Component {constructor (props) {super (props);} _ setTitle () {const {id} = this.props; switch (id) {case 0: return 'Submit' Case 1: return 'Draft'; case 2: return' Delete'; default: return 'Submit' }} render () {let title = this._setTitle () Return ({title})}} Button.propTypes = {id: PropTypes.number OnPress: PropTypes.func.isRequired} export default class SomeContainer extends Component {constructor (props) {super (props) This.state = {username:null}} _ submit () {if (this.state.username) {console.log (`Hello, ${this.state.username}! `);} else {console.log ('Please, enter username') }} render () {return (}}

We have "upgraded" the Button component. Replace the attribute "title" with a new attribute called "id". Now Button components have become "flexible". Pass 0-button component to display "submit". Pass 2-displays "delete". But there may be some problems.

Button is created as a dumb component-just to display the data, which is done by its higher-level components.

If we pass 5 to this component as id, we need to update the component to adapt it to the change. Dumb components, that is, subdivided widgets, as long as it receives props, if there is a state should also have nothing to do with the global.

7. Inline style

After using the RN layout, I encountered a writing style problem with inline style. Something like this:

Render () {return ();}

When you write like this, you think, "write like this for now, after I run it in the simulator-if the layout is fine, move the style to a separate module." Maybe it's a good idea. But... Unfortunately, you tend to selectively ignore in-line styles.

Be sure to write styles in separate modules, away from inline styles.

8. Validate the form using redux

To use redux to validate the form, I need to create a separate field of action,actionType in reducer, which is troublesome.

So I decided to use only state to complete the verification. There is no reducers,types and so on, just pure functions at the container level. This strategy helps me a lot by removing unnecessary functions from action and reducer files.

9. Over-reliance on zIndex

Many people move from web development to RN development. There is a css attribute z-index in web that helps us display what we want at the level we need.

In RN, there is no such feature at first. But then it was added. At first, it was easy to use. Just set the zIndex attribute for the element and it will render in any layer order you want. But after testing on Android... Now I only use zIndex to set the structure of the presentation layer.

10. Do not carefully read the source code of external components

You can introduce external components to save your development time.

But sometimes the module may be interrupted or may not work as described. Read the source code and you will understand what went wrong. Maybe there's something wrong with the module itself, or maybe you just used it wrong. In addition-if you read the source code of other modules carefully, you will learn how to build your own components.

11. Be careful with gestures and Animated API.

RN provides us with the ability to build fully native applications. How to make users feel like a native application? Page layout, sliding gestures, or animation?

When you use the default modules provided by View,Text,TextInput and other RN, gestures and animations should be handled by PanResponder and Animated API.

If you are a rn development engineer transferred from web, it may be difficult to get the user's gestures, you need to distinguish when to start and when to end, long press and short press. You may not know enough about how to simulate these animation operations in RN.

This is the Button component I built with PanResponder and Animated. This button is built to capture user gestures. For example-the user presses the item and then drags his finger to one side. When the button is pressed, with the help of the animated API, build a change in opacity under the button press:

'use strict'; import React, {Component, PropTypes} from' react'; import {Animated, View, PanResponder, Easing} from 'react-native'; import moment from' moment'; export default class Button extends Component {constructor (props) {super (props); this.state = {timestamp: 0}; this.opacityAnimated = new Animated.Value (0) This.panResponder = PanResponder.create ({onMoveShouldSetPanResponderCapture: (evt, gestureState) = > true, onStartShouldSetResponder: () = > true, onStartShouldSetPanResponder: () = > true, onMoveShouldSetPanResponder: (evt, gestureState) = > true, onPanResponderMove: (e, gesture) = > {}, onPanResponderGrant: (evt, gestureState) = > {/ * THIS EVENT IS CALLED WHEN WE PRESS THE BUTTON**/ this._setOpacity (1) This.setState ({timestamp: moment ()}); this.long_press_timeout = setTimeout (() = > {this.props.onLongPress ();}, 1000) }, onPanResponderStart: (e, gestureState) = > {}, onPanResponderEnd: (e, gestureState) = > {}, onPanResponderTerminationRequest: (evt, gestureState) = > true, onPanResponderRelease: (e, gesture) = > {/ * THIS EVENT IS CALLED WHEN WE RELEASE THE BUTTON**/ let diff = moment (). Diff (moment (this.state.timestamp)); if (diff)

< 1000){ this.props.onPress(); } clearTimeout(this.long_press_timeout); this._setOpacity(0); this.props.releaseBtn(gesture); } }); } _setOpacity(value){ /**SETS OPACITY OF THE BUTTON**/ Animated.timing( this.opacityAnimated, { toValue: value, duration: 80, } ).start(); } render(){ let longPressHandler = this.props.onLongPress, pressHandler = this.props.onPress, image = this.props.image, opacity = this.opacityAnimated.interpolate({ inputRange: [0, 1], outputRange: [1, 0.5] }); return( {image} ) } } Button.propTypes = { onLongPress: PropTypes.func, onPressOut: PropTypes.func, onPress: PropTypes.func, style: PropTypes.object, image: PropTypes.object }; Button.defaultProps = { onPressOut: ()=>

{console.log ('onPressOut is not defined');}, onLongPress: () = > {console.log (' onLongPress is not defined');}, onPress: () = > {console.log ('onPress is not defined');}, style: {}, image: null}; const styles = {mainBtn: {width:55, height:55, backgroundColor:'rgb (255255255)',}}

First, initialize the PanResponder object instance. It has a different set of operation handles. I am interested in onPanResponderGrand (triggered when the user touches the button) and onPanResponderRelease (triggered when the user moves his finger away from the screen).

I also set up an instance of an animated object to help us deal with animation. Set its value to zero; then we define the _ setOpacity method, which changes the value of this.opacityAnimated when called. Before rendering, we insert a normal opacity value of this.opacityAnimated. Instead of using View, we use the Animated.View module in order to use dynamically changing opacity values.

From the above example, you will find that Animated API is not difficult to understand, you only need to read the relevant API documentation to ensure that your application is running. I hope this example will get you off to a good start.

The above is all the contents of the article "what mistakes will be encountered in developing with React Native/Redux". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, 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

Development

Wechat

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

12
Report