我如何在React Native中渲染一个元素,该元素随后不受任何其他渲染/状态更新的影响?
我想要实现的目标:
我有一个按钮。每次您按下该按钮时,页面上某处的数字都会增加1。此外,当按下同一按钮时,会在1秒钟内显示一个浮动的“ +1”,此后它将消失。 “ +1”与总数无关。如果按下按钮5次,我想看到5个浮动的“ +1”。
我正在状态中存储(并删除)浮动的“ +1”。但是,每次我通过单击按钮添加一个时,浮动的“ +1”都会重新渲染并重新启动其动画。我该如何在单击按钮时渲染这些元素,而不能在再次单击按钮时重新渲染它们?
“ + 1”是一个类,用于在componentDidMount上启动动画。
现在情况: Buttonclick->更新状态->呈现浮动的“ +1”-> Buttonclick->更新状态->呈现所有浮动的“ +1”
期望的情况 Buttonclick->更新状态->呈现浮动的“ +1”-> Buttonclick->更新状态->仅呈现新添加的浮动“ +1”
答案 0 :(得分:1)
我在这里草拟了一些,希望它能对您有所帮助:MP3 spec
基本上,您在状态中的数组中有一些elems
,有一个<button>
会向该数组中添加新元素,并且每次添加元素时,您还会创建一个{{ 1}},一旦超时结束,它将自己从数组中删除。代码如下:
将超级基本数组设置为以下状态:
setTimeout
从状态渲染元素:
state = {
elems: []
};
在状态中添加元素(在文章底部有更详细的说明):
render() {
// pretty basic, just a normal button to add elements & map through state to render
return (
<>
<button onClick={this.addElem}>Add elem!</button>
{this.state.elems.map((elem, i) => (
<p key={i}>{elem.text}</p>
))}
</>
);
}
从状态中删除元素
addElem = () => {
const elems = [...this.state.elems];
// create empty id to be filled later
let timeoutProps = { id: null };
// set timeout for element to be removed
const timeoutId = setTimeout(
({ id }) => {
this.removeElem(id);
},
1000,
timeoutProps
);
// quickly add timeout id to props, which will get passed back in to timeout
timeoutProps["id"] = timeoutId;
// add new element to "elems" array
elems.push({
text: `New!! (${timeoutId})`,
id: timeoutId
});
// update state
this.setState({ elems });
};
removeElem = id => {
let elems = [...this.state.elems].filter(elem => elem.id !== id);
this.setState({ elems });
};
非常简单,但是如果您对此有疑问,请告诉我。我的代码中最时髦的部分是render
方法。我想确保在创建超时后保存addElem
,并且在超时到期后,可以通过将超时ID传递给timeoutId
函数来对其进行调用。
为了将超时的id传递给removeElem
(在超时到期之后),我不得不对JavaScript对象有些棘手。
removeElem
属性的对象:id
let timeoutProps = { id: null };
变量只是指向数据timeoutProps
的指针。因此可以在其他地方进行更改,以后{id: null}
的任何使用都会使用更新后的数据。timeoutProps
回调。
setTimeout
属性timeoutProps
编辑为timeoutId
id
回调 still ,因此setTimeout
变量现在指向更新后的数据{{1 }} timeoutProps
回调,{id: timeoutId}
现在就可以访问setTimeout
,并且可以将setTimeout
传递给{id: timeoutId}
。 希望这有意义吗?这是有关Javascript:D的令人困惑(且有趣)的事情之一,如果需要的话,可以解释更多。
答案 1 :(得分:0)
您可以在shouldComponentUpdate()
中控制渲染。是否渲染的决定取决于您:如果shouldComponentUpdate
返回false,则不会进行渲染;否则,不会渲染。如果返回true-组件将重新呈现。