【发布时间】:2020-10-02 15:49:16
【问题描述】:
this.state.topText 和 this.state.bottomText 的值总是落后一个变化。例如,如果我在 topText 的输入框中输入 1234,this.state.topText 的值将是 123。 react 文档说要修复异步更新,我们应该使用接受函数而不是对象的 setState() 形式。我已经做到了,setState 的价值仍然滞后。如何修复 handleChange() 中的 setState()?
App.js
import React from "react";
import MemeGenerator from "./MemeGenerator"
import "./styles.css";
class App extends React.Component {
constructor() {
super();
this.state = {
topText:"",
bottomText: "",
imgs: [],
imgUrl:""
};
this.handleChange=this.handleChange.bind(this)
this.handleClick=this.handleClick.bind(this)
}
handleChange(event) {
const {name, value} = event.target
this.setState((prevstate) => ({
...prevstate,
[name]: value
}));
document.getElementById('tt').innerHTML=this.state.topText;
document.getElementById('bt').innerHTML=this.state.bottomText;
}
handleClick(target){
const imgNum=this.state.imgs.length;
const randNum=Math.floor(Math.random()*imgNum)
this.setState((prevState)=>{
return {imgUrl: prevState.imgs[randNum].url }
})
}
componentDidMount(){
fetch('https://api.imgflip.com/get_memes')
.then((response)=> response.json())
.then((data)=>{
const randImg=data.data.memes
this.setState(()=>{
return{imgs: randImg}
})
})
}
render() {
return (
<MemeGenerator
handleChange={this.handleChange}
handleClick={this.handleClick}
topText={this.state.topText}
bottomText={this.state.bottomText}
imgUrl={this.state.imgUrl}
/>
);
}
}
export default App;
MemeGenerator.js
import React from "react"
function MemeGenerator(props){
return(
<div className="App">
<h1>Meme Generator</h1>
<input
type="text"
name="topText"
value={props.topText}
onChange={(event)=>props.handleChange(event)}
/>
<input
type="text"
value={props.bottomText}
name="bottomText"
onChange={(event)=>props.handleChange(event)}
/>
<button onClick={(event)=>props.handleClick(event.target)}>Gen</button>
<img
src={props.imgUrl}
alt=""
width="300"
/>
<p id="tt"></p>
<p id="bt"></p>
</div>
)
}
export default MemeGenerator
【问题讨论】:
-
setState不保证是同步的。这在the official documentation 中有很好的介绍
标签: javascript reactjs