Javascript React setState两次渲染状态
当我与setState交易时,它会转两次。首先返回数据Fail,然后返回数据Ready。控制台首先返回false,然后返回true。我只想在控制台中返回trueJavascript React setState两次渲染状态,javascript,reactjs,fetch,fetch-api,Javascript,Reactjs,Fetch,Fetch Api,当我与setState交易时,它会转两次。首先返回数据Fail,然后返回数据Ready。控制台首先返回false,然后返回true。我只想在控制台中返回true export default class App extends React.Component { constructor(props) { super(props); this.state = { loading: false, data: []
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
loading: false,
data: []
};
}
componentDidMount() {
fetch("https://reqres.in/api/users?page=2")
.then(res => res.json())
.then(result => {
this.setState({
data: result.data,
loading: true
});
});
}
render() {
const { loading } = this.state;
console.log(loading);
const dataReady = <div>Data Ready </div>;
const DataFail = <div>Data Fail </div>;
return <div>{loading === true ? dataReady : DataFail}</div>;
}
}
导出默认类App扩展React.Component{
建造师(道具){
超级(道具);
此.state={
加载:false,
数据:[]
};
}
componentDidMount(){
取回(“https://reqres.in/api/users?page=2")
.then(res=>res.json())
。然后(结果=>{
这是我的国家({
数据:result.data,
加载:正确
});
});
}
render(){
const{loading}=this.state;
控制台日志(加载);
const dataReady=数据就绪;
const DataFail=数据失败;
返回{loading==true?dataReady:DataFail};
}
}
例如:
这是由于React的生命周期以及您最初将state.loading属性设置为false
首先是初始渲染,然后调用componentDidMount及其setState。您可能希望保持加载未定义,然后在render方法中检查其是否已定义,然后再检查其值。您只需反转与加载关联的布尔值。加载数据时,首先应将其设置为
true
,然后设置为false
工作示例:
类应用程序扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
加载:对,
错误:false,
数据:[]
};
}
componentDidMount(){
取回(“https://reqres.in/api/users?page=2")
.then(res=>res.json())
。然后(结果=>{
这是我的国家({
数据:result.data,
加载:错误
});
})
.catch(错误=>{
this.setState({error:true});
});
}
render(){
const{loading,error}=this.state;
!正在加载和控制台.log(true)
返回{!正在加载&数据准备就绪}
{错误和数据错误:(}
;
}
}
ReactDOM.render(,document.getElementById('root'))
您的数据发生了更改,这就是为什么您有两条消息: 你需要做决定,你打算怎么做?
如果您不想更改状态,您可以使用
shouldComponentUpdate
,或者您可以跳过一条控制台消息您所说的只想返回true是什么意思?是的,只返回true。您的意思是这样的吗?您不能在控制台中只返回true。因为加载的初始状态为false。因此,这将在初始状态之前显示在控制台中在那之后,它将变为true。您应该查看lifecyce函数shouldComponentUpdate()我如何在不使用componentDidMount的情况下使用shouldComponentUpdate?您可以保留componentDidMount,然后添加shouldComponentUpdate。我想我无法准确解释这个问题。我只想在控制台上返回true,我的初始值将为false。您只想在加载数据时返回true?给您,现在是您的组件日志true
加载数据时,我需要在“渲染”下执行控制台过程。好的,我不知道这是必要的,但现在开始。渲染任何已完成加载的内容的条件只是!加载