我在問一個基本的問題,但我是一個菜鳥,甚至無法在谷歌中找到答案,所以請溫柔點??。我正在嘗試使用 setstate,但我不知道為什么我的狀態仍然為空。這是代碼:
import React, {Component} from 'react';
import Ball from './Ball'
class Lottery extends Component{
constructor(props){
super(props);
this.state = { nums : []};
this.RenderNums = this.RenderNums.bind(this);
this.RenderNums();
}
RenderNums(){
let ballnum = this.props.ballnum;
let maxnum = this.props. maxnum;
let arrnums = Array.from({length: ballnum}, () => Math.floor(Math.random() * maxnum) 1);
console.log(arrnums);
this.setState({nums : arrnums});
}
我試圖將我的亂數陣列放入狀態,為此我在建構式中呼叫一個函式,但是在 npm start 并查看開發工具后,我的狀態 nums 是一個空陣列。亂數陣列創建得很好并被列印到控制臺。有人可以通過查看代碼來判斷我做錯了什么嗎?如有必要,我會嘗試將其放在 codepen 上。
uj5u.com熱心網友回復:
setState如檔案中所述,您不應在建構式中呼叫或產生任何副作用:
您不應在建構式() 中呼叫setState()。相反,如果您的組件需要使用本地狀態,請直接在建構式中將初始狀態分配給 this.state
相反,直接分配初始狀態或使用專用生命周期,您應該嘗試componentDidMount.
class Lottery extends Component {
constructor(props) {
super(props);
this.state = {
nums: Array.from(
{ length: this.props.ballnum },
() => Math.floor(Math.random() * this.props.maxnum) 1
),
};
}
// or
RenderNums = () => {...}
componentDidMount() {
this.RenderNums();
}
}
uj5u.com熱心網友回復:
將this.RenderNums();呼叫放入componentDidMount () {}方法中。
class Lottery extends Component{
constructor(props){
super(props);
this.state = { nums : []};
this.RenderNums = this.RenderNums.bind(this);
//this.RenderNums();
}
componentDidMount(){
this.RenderNums();
}
RenderNums(){
let ballnum = this.props.ballnum;
let maxnum = this.props. maxnum;
let arrnums = Array.from({length: ballnum}, () => Math.floor(Math.random() * maxnum) 1);
console.log(arrnums);
this.setState({nums : arrnums});
}
componentDidMount 相當于函陣列件中的 useEffect。您不應該在建構式中呼叫 setState。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/380168.html
標籤:javascript 反应
