Learning goals
After learning about the environment setup and demo running in RN, we are going to look at two important elements that affect page changes: props and state
Code debugging
Before introducing these two brothers, I would like to introduce the running and debugging methods of demo, and then I will introduce breakpoint debugging and browser debugging in detail
After the react-native run-Android is executed successfully, if you want to modify the page and modify the code logic to see the effect, you do not need to run it again like the original. If the Android project has a lot of moudle, the building time is really long.
-
Shake it to bring up a menu that enables Live Reload
-
In the lower left corner of VSCode, go to the command panel and search React Native: Start Packager
-
Once it’s started up, you can try to modify the code and save it manually CTRL + S will automatically update the code and you can see what it looks like
Debugging said, let’s introduce the brothers
props :
Personally, I understand the value of this attribute is a reference in the parent component subcomponents when specified, the attribute is defined in the child components, such as components to create a new apple, apple has a color attribute, in constructing the component, specify a color attribute, when used in the parent component specifies the color of a specific value, then the last child components will get the value, show Show the apples of the corresponding color.
For example:
Create a new AppleComponent, AppleComponent
import * as React from "react";
import { Text, View } from "react-native"; /** * Define properties interface */ interface AppleComponentProps{// Apple component color attribute apple_color:string} /** * Define an Apple component */export default class AppleComponent extends React.Component<AppleComponentProps>{
constructor(props:any){
super(props);
}
render(){// What color is the parent componentreturn(<View> <Text> I am an Apple component {this.props. Apple_color} </Text> </View>)}}Copy the code
We define a property apple_color in the Apple component to set its color
Use this.props. Apple_color to get the value specified by the parent component in render
// Import AppleComponent from your own path'./src/Apple'// This component is the home page component of the startupexport default class App extends Component<Props> {
render() {
return (
<AppleComponent apple_color="Red"/ >); }}Copy the code
See, this sentence refers to the child component and specifies the property value of the child component. The value is set here, and is fixed when passed to the child component.
I’m just passing one attribute, but there are a lot of them, so it’s a little bit of a hassle to pass them one by one and now I’m going to post multiple attributes
Interface AppleComponentProps{// Apple component color attribute apple_color:string // Apple_weight :number // Apple component price attribute Apple_price :number} /** * A custom Apple component */export default class AppleComponent extends React.Component<AppleComponentProps>{
constructor(props:any){
super(props);
}
render(){// What color is the parent componentreturn</Text> I am an Apple component {this.props. Apple_color} </Text> <Text> I am an Apple component {this.props. Apple_weight}kg</Text> <Text> mY price is :{this.props. Apple_price} yuan </Text> </View>)}}Copy the code
export default class App extends Component<Props> {
render() {
return (
<AppleComponent apple_color="Red"Apple_price apple_weight = {1.8} = {} 9.9 / >); }}Copy the code
On the basis of one parameter, two attributes are successively added, using the same method as above. It can be seen that it is more troublesome to write the attribute values passed in the case of a large number, and a relatively simple writing method is posted below
export default class App extends Component<Props> {
render() {
var params = { apple_color :'red', apple_weight: 1.8, apple_price: 9.9}
return (
<AppleComponent {...params}/>
);
}
}
Copy the code
{… Params} means passing all the parameters together, which makes it much easier.
Of course, sometimes you can pass only part of the attributes. Use destruct assignment
export default class App extends Component<Props> {
render() {
var params = { apple_color :'red',apple_weight: 1.8, apple_price: 9.9} var {apple_color,apple_weight} = paramsreturn( <AppleComponent apple_color={apple_color},apple_weight={apple_weight}/> ); }}Copy the code
But writing it this way the compiler will tell you that there’s an error that there’s a property missing, because here I’m using the interface to define the property and passing it through the generic
Interface AppleComponentProps{// Apple component color attribute apple_color:string // Apple_weight :number // Apple component price attribute apple_price:number }exportdefault class AppleComponent extends React.Component<AppleComponentProps>{... }Copy the code
Therefore, with the qualification of the interface, only according to the specification of the interface can not lack of attributes, all to be overridden.
What if you are stubborn and don’t want to pass all attribute assignments? Ok, after exploring, yes, those of you who know Kotlin should know that there is a void property, use? Identity, yeah, same thing, we just need to put a nullable identifier on the property, and then the property can not be passed.
apple_price? :numberCopy the code
So you don’t get an error
The other way is to pass an any value to a generic without using an interface.
React.Component<any>
Copy the code
And then you’ll notice that if some of the properties aren’t specified, then some of the stuff that’s supposed to be displayed on the UI, because some of the parameters aren’t passed, is going to be empty, so there’s a way to set the default values for the properties to keep them from being empty and this is just for the sake of learning that you don’t actually have to use them
Static defaultProps = {apple_color:"Green", apple_weight: 2.5, apple_price: 19.9}; Private apple_color: string = private apple_color: string ="Green"; Private apple_weight: number = 2.5; Private apple_price: number = 19.9; // The constructor assigns this.apple_color = this.props. Apple_color; this.apple_weight = this.props.apple_weight; // This.apple_price = this.props. Apple_price? this.props.apple_price:this.apple_priceCopy the code
Put the default value at the very beginning of the component and if the parent component doesn’t assign a value, then the default value is displayed and only the price is not passed in, so the default price is used
Above is my understanding of the props, has there been a constraint attribute types limit types of content, the feeling, in a nutshell, temporarily encounter useful place behind again in detail, is actually on the attribute type of the types specified, if the specified attribute values when types do not match, the compiler will prompt error.
First add the dependency libraries
yarn add prop-types
Copy the code
Importing from components
import PropTypes from "prop-types";
Copy the code
Component examples
The static propTypes = {name: propTypes. String. IsRequired, / / isRequired is not empty Will pass attribute age: PropTypes. Number, / / specified numeric type sex: Proptypes. string // Specify string type};Copy the code
There is a lot more to understand about props, so we need to learn how to use it quickly.
state:
The object state is used to control the page state update, and the props is an external assignment. Once an assignment is made, the props will not change the edge after being received in the component
For example
In the case of the apple component above, the color, price, and weight are all attributes that specify the component, and the style is defined before initialization. If you want to change the state of the Apple component after this, for example, click the Apple component to change the color or change its display content, etc
It’s actually used more for loading network data
Change the style (color and quantity) of the apple component every 1s
Interface AppleComponentState {// Whether to change color ischange: Boolean; // Number of apples apple_num: number; } // Pass the props property interface object corresponding to the front P in the generic of Component<P,S>exportdefault class AppleComponent extends React.Component<AppleComponentProps,AppleComponentState> {.... }Copy the code
Assignment of state variables in constructors
// Constructor (props: AppleComponentProps) {super(props); // Attribute = this.apple_color = this.props. Apple_color; this.apple_weight = this.props.apple_weight; this.apple_price = this.props.apple_price? This.props. Apple_price: this.props. Apple_price: this.props.false, apple_num : 1 }; // Execute the state change functionsetInterval(() => {
this.setState(previousState => {
return{ ischange: ! previousState.ischange, apple_num: previousState.apple_num + 1 }; }); }, 1000); }Copy the code
SetInterval () dynamically changes ischange,apple_num to refresh the display. This.setstate () is called to change the state of the apple component. PreviousState refers to the last state object. Each setState will store a state object in a queue of objects, like a stack.
Here is the render reference code, which is a call to the status variable this.state.xxxxx to get the latest value after the status update
render() {// What color can the parent component uselet colorvalue = this.state.ischange ? "#ff0033" : "# 000000";
return( <View style={styles.container}> <Text style={{ color: Colorvalue}}> I am a {this.apple_color} apple component </Text> <Text style={{color: colorvalue}}> MY weight is: {this.apple_weight} kg </Text> <Text style={{color: colorvalue}}> < font style={{fontSize: 20, margin: 10, color: RGB (0, 0, 0); colorvalue }}> {this.state.apple_num} </Text> </View> ); }Copy the code
The above is to understand the use of state through an example, which is rarely used in actual application development. The following is a simple business of actual application development to practice the use of State. Request a list of articles through the network to display the data and see the effect first
Step 1: Define properties and states Before you analyze it, though it’s simple, get a list of data to display via a network request
What are some of the attributes that might be used in this?
Properties: Variables used to control the business logic of a function
- Url :string // Interface request address
- curPageIndex; Number // Current page number index
- PageSizes :number // Data size per page
- .
Do pagination load pull down refresh pull up load more and so on will be used a lot and add as needed
State: Variables that are used to refresh the interface
- Data :[] // The data source must have and is only required
- .
Here is the property and state reference code defined to achieve a pure presentation of list data:
// attribute interface HomeArticalProps {// Interface address artical_url? : string; // Current page index page_index? : number; } // state interface HomeArticalStates {// Article data source data: string[]; } // passed into the genericexportdefault class HomeArtical extends React.Component< HomeArticalProps, HomeArticalStates > {...... }Copy the code
If you want to use an interface to define a property state, you can use this.props. XXXX to get the value of the property passed to the external parent. There is also a property prompt and error check in the vscode editor. Since I just learned it, I also refer to my colleagues’ code to write it. I’m going to look at typescript documentation, so don’t confuse people who don’t know typescript to look at typescript documentation. Interfaces that declare merging merge TypeScript documents
Let’s go ahead and assign once we’ve defined the properties and states
Some initial values are assigned by default
Private page_index: number = 0; Private artical_URL: string ="http://www.wanandroid.com/article/list/"; Private artical_API: string = this.artical_url + this.page_index +"/json";
Copy the code
Constructors assign values to properties and states from the parent component or from the default values themselves
constructor(props: HomeArticalProps) { super(props); // this. Artical_url = this.props. Artical_url? this.props.artical_url : this.artical_url; this.page_index = this.props.page_index ? this.props.page_index : this.page_index; this.artical_api = this.artical_url + this.page_index +"/json"; This. state = {// data source data: []};Copy the code
This interface only needs to use a list component to use the native FlatList reference code:
// Render page publicrender() {
return<FlatList // List component style={styles.container} // Style data={this.state. Data} // Bind data source keyExtractor={this._keyExtractor} {this.renderHeader} // List header view ItemSeparatorComponent={this.renderSeparator} / RenderItem ={this.renderitem} //item item />); }Copy the code
Write network requests using a native FETCH
Private getArticalDatas(curPage: Number) {fetch(this.artical_API).then(response => response.json()).then(responseData => {this.setstate ({// modify data source Data: this.state.data.concat(responsedata.data.datas)}); }) .catch(error => { this.setState({}); }); }Copy the code
Start requesting data
The life cycle of the component starts loading data after the interface rendering is complete
// Start requesting datacomponentDidMount() {
this.getArticalDatas(0);
}
Copy the code
At this point the page is complete, of course loading and pull-up loading and pull-down refreshing will be more complete. I wrote the JS version earlier, but I will change it to TS. I haven’t changed it yet. This time, learn the use and personal understanding of properties and states.
Writing so much is actually the most basic usage, in-depth understanding of things to be slowly understood in the actual project. This is a quick learning, hands-on project development notes, used to deepen memory, if there is a study together can join me. Keep updating.
Plan for later study
- Page skipping and parameter passing third party library use
- Declarations that reference JS in TSX
- Mobx state management
- Code debugging
- Packaging releases
- Hot update
- Performance optimization and in-depth understanding
- .
To view the full demo code, go to my Github address :RNDemo