Javascript 有没有办法避免在我的代码中使用forceupdate?
我有这样一段代码:Javascript 有没有办法避免在我的代码中使用forceupdate?,javascript,reactjs,jsx,Javascript,Reactjs,Jsx,我有这样一段代码: randomArray(arrayOfImage){ //algorithm goes here return shuffledArray; } shuffle(){ this.randomArray(images); this.forceUpdate(); } render(){ let array = this.randomArray(images)
randomArray(arrayOfImage){
//algorithm goes here
return shuffledArray;
}
shuffle(){
this.randomArray(images);
this.forceUpdate();
}
render(){
let array = this.randomArray(images); //images is a declared array
let squares = array.map((item,index) => <Squares/> )
return(
<div>
<div id='square-container'>
{squares}
</div>
<button className='btn' onClick = {this.shuffle.bind(this)}>Shuffle</button>
</div>
)
}
randomArray(arrayOfImage){
//算法在这里
返回随机数组;
}
洗牌(){
随机数组(图像);
这个.forceUpdate();
}
render(){
让array=this.randomArray(images);//images是声明的数组
让正方形=数组.map((项,索引)=>)
返回(
{squares}
洗牌
)
}
基本上,我声明了一个数组images
。函数randomArray()
返回图像的混洗版本。然后,对于洗牌数组array
中的每个项目,浏览器将使用给定的道具呈现一个div
现在我有一个按钮,用户可以自己洗牌数组。在这里,我使用forceupdate()
,因为即使在单击按钮时数组被洗牌,DOM也不会更新,因为状态没有变化
它起作用了!但是,既然不鼓励使用
forceupdate()
,我应该如何减少这一点。。。比如说,业余?当然,React会在元素的状态发生更改时,或者从其父组件(或状态库)接收新道具时,再次渲染元素
您可以阅读有关react如何在中处理渲染的详细信息
因此,要处理这个问题,只需在原始数组的基础上创建一个新数组,然后再次将其设置为状态
在过去,您需要一个组件级的类
const target=document.getElementById('container');
类ArrayOfImages扩展React.Component{
构造函数(){
//别忘了给super打电话
超级();
//设置初始状态
此.state={
图像:[
'https://c402277.ssl.cf1.rackcdn.com/photos/18357/images/featured_story/Medium_WW252652.jpg?1576698319',
'https://c402277.ssl.cf1.rackcdn.com/photos/882/images/circle/African_Elephant_7.27.2012_hero_and_circle_HI_53941.jpg?1345532748',
'https://c402277.ssl.cf1.rackcdn.com/photos/1732/images/circle/Asian_Elephant_8.13.2012_Hero_And_Circle_HI_247511.jpg?1345551842'
]
};
//绑定我们将从渲染函数调用的函数
this.shuffle=this.shuffle.bind(this);
}
洗牌{
//创建状态对象的浅层副本
const copyOfState=this.state.images.slice();
//稍微洗一下(Durstenfeld shuffle:http://en.wikipedia.org/wiki/Fisher-Yates_shuffle#The_modern_algorithm)
for(设i=copyOfState.length;i--;){
让target=Math.floor(Math.random()*(i+1));
[copyOfState[i],copyOfState[target]=[copyOfState[target],copyOfState[i]];
}
//使用新阵列更新现有状态
this.setState({images:copyOfState});
}
render(){
const{images}=this.state;
返回(
一些大象
{images.map(img=>)}
洗牌图像
);
}
}
ReactDOM.render(,目标)代码>
它是返回一个洗牌数组,还是将提供的数组洗牌到位?根据shuffle中的用法,它似乎是后者。为什么不让数组成为状态的一部分,并在洗牌时创建一个新的数组来更新状态?是的,使用本地状态,或者某种形式的状态库,所以你是说我应该使用数组作为状态的一部分?我一直认为这是一种糟糕的编码方式:DIt dependens:)这并不意味着您的数据是静态的,您可以有一个填充状态的加载事件(之后它也会重新渲染),或者数据来自上面的道具,但您只对显示/洗牌父级提供的数组感兴趣(因此,您也可以洗牌索引)