Don’t know why, since I began to write some of my work and life here minutes later, the boss started to all let me do some amazing things, does he know (mutter), though I know not possible, the old boy besides daughter-in-law children let him up, absolutely can’t take mobile phone to see the article (this sentence is to test, If he did read my articles, I would hardly be updating them. Ha ha ha ha ha) this is a development of actual combat, just with the help of our project, when I played and the code before submitting the Git, so use them directly this time, in the words of colleagues, I am a kit, have a lot of code to use, can be directly CV today will introduce you to our daily application more React, Mainly in the following aspects
- How to implement background calls in React
- The React parent component transmits values
- React How to modify the deep state property
Well, the same rules, before the formal look at the code, first to give me a point of concern + comment, thank you for supporting personal public number: Java architect alliance, daily update technology learning good article
React How to call the background
Used to using jQuery wrapped ajax methods, React project development was a bit of a worry, note.
fetch
Fetch is used to replace the traditional XMLHttpRequest. It has many advantages, including syntax for chain calls, returning promises, and so on.
Here is the basic fetch usage, which is asynchronous by default.
fetch(url,{
method: 'POST'.headers: {
'Content-Type': 'application/json',},body: data, // Data is the transfer object
}).then(res= > {
res.json().then(data= > { // Data is the returned object
console.log(data);
});
}).catch(function(e) {
console.log("ERROR");
});
Copy the code
Concise version:
let option = {}; / / parameters
options.method = 'post';
let data={};
options.body = JSON.stringify(data);
options.headers={
'Content-Type':'application/json'
};
fetch(url,option).then(res= > res.json())
.then(data= > console.log(data))
.catch(e= > console.log("error", e))
Copy the code
How to synchronize calls
Use async and await keywords, but I heard it is not compatible with browsers.
// Add async keyword before method
async function fetchAsync () {
let response = await fetch(url);
let data = await response.json();
return data;
}
Copy the code
The real case
getData=(id) = >{
let option = {}; / / parameters
options.method = 'post';
let data={id:id};
options.body = JSON.stringify(data);
options.headers={
'Content-Type':'application/json'
};
fetch(baseUrl+"/xx/xxxx",option)
.then(res= > res.json())
.then(res= > {
if(res.status===200) {// Get the return value and change the state
this.setState({
data:res.data.list
});
}
})
.catch(e= > console.log("error", e));
}
Copy the code
The React parent component transmits values
-
- Parent component passes value to child component
- Child components pass values to parent components
Parent component passes value to child component
(props).props (props).props (props).props (props) The child component is processing the value passed by the parent component.
// Create the parent component first
class ParentCom extends React.Component{
constructor(props){
super(props)
this.state=({
content:'Pass input to child'.zi_content:' ' // This is the value to be passed})}// The parent component uses this method to put the value that needs to be passed into state.
giveValue = (e) = >{
let value = document.getElementById("fu_input").value;
this.setState({
zi_content : value
});
}
render(){
return(
<div>
<Button onClick={this.giveValue}>Give the child the value</Button>
<Input id="fu_input" defaultValue={this.state.content}></Input>{/* Pass the required value to the child component */}<ChildCom zi_content = {this.state.zi_content}/>
</div>)}}// Create a child component
class ChildCom extends React.Component{
constructor(props){
super(props)
}
render(){
let val = ' ';
if(this.props.zi_content){
// Get the value passed by the parent component in props
val = this.props.zi_content
}
return(
<div>
<div>I am a child</div>
<Input defaultValue={val} value={val}></Input>
</div>
)
}
}
ReactDOM.render(
<ParentCom />.document.getElementById('root'))Copy the code
Child components pass values to parent components
Since the child component cannot handle the state of the parent component directly, we can change the state of the parent component through methods of the parent component.
// Create the parent component
class FuCom extends React.Component{
constructor(props){
super(props)
this.state=({
zi_value:""})}// The parent component definition method can change the value of the parent component and pass this method to the child component
changeData = (msg,e) = >{
this.setState({
zi_value:msg
})
}
render(){
return(
<div>Values passed by the child component:<span>{this.state.zi_value}</span>{/* Pass functions that modify the parent component's data to the child component */}<ZiCom changeData={this.changeData}/>
</div>)}}// Create a child component
class ZiCom extends React.Component{
constructor(props){
super(props)
this.state=({
input_val:"Initial contents of child components"})}// The child receives a method from the parent that modifies the value of the parent
sendData = (e) = >{
let val = document.getElementById("inputId").value;
this.props.changeData(val)
}
render(){
return(
<div>
<Input type="text" id="inputId" defaultValue={this.state.input_val} ></Input>
<Button onClick={this.sendData}>To the parent value</Button>
<Button onClick={(e)= >{this.props. ChangeData ('Hello world',e)}}> Directly pass the props function</Button>{/ *<Button onClick={function(e){this.changeData('dd',e)}.bind(this)} >Es6 binding functions are not used</Button>* /}</div>
)
}
}
ReactDOM.render(
<FuCom />.document.querySelector('#root2'))Copy the code
Modify the deep state attribute
Environment encountered:
this.state=({
key:1.funcTree:null.checkedKeys: [].searchCard: {searchCard:"",,
cardKey:0.selectedKey:"".expandKeys: []},drawer: {drawerKey:1.isShow:false.data: [1.2.3]}});Copy the code
The above state contains multiple layers of data structures, when you are trying to change a substructure as follows:
this.setState({
drawer: {isShow:true}});Copy the code
It will cause other properties under the drawer to be lost.
Solution:
this.state.drawer.isShow = true;
this.setState(
this.state
);
Copy the code
This preserves other attributes.