【发布时间】:2019-04-08 08:25:40
【问题描述】:
下面是两个几乎做同样事情的 React 组件。一是函数;另一个是一个类。每个组件都有一个 Animated.Value 和一个异步侦听器,该侦听器在更改时更新 _foo。我需要能够访问功能组件中的_foo,就像我在经典组件中访问this._foo 一样。
-
FunctionalBar不应在全局范围内有_foo,以防有多个FunctionalBar。 -
FunctionalBar不能在函数范围内包含_foo,因为每次FunctionalBar呈现时都会重新初始化_foo。_foo也不应该处于状态,因为当_foo更改时组件不需要渲染。 -
ClassBar没有这个问题,因为它在组件的整个生命周期中保持_foo在this上初始化。
如何在FunctionalBar 的整个生命周期内保持_foo 的初始化而不将其置于全局范围内?
功能实现
import React from 'react';
import { Animated, View } from 'react-native';
var _foo = 0;
function FunctionalBar(props) {
const foo = new Animated.Value(0);
_onChangeFoo({ value }) {
_foo = value;
}
function showFoo() {
let anim = Animated.timing(foo, { toValue: 1, duration: 1000, useNativeDriver: true });
anim.start(() => console.log(_foo));
}
useEffect(() => {
foo.addListener(_onChangeFoo);
showFoo();
return () => foo.removeListener(_onChangeFoo);
});
return <View />;
}
经典实现
import React from 'react';
import { Animated, View } from 'react-native';
class ClassBar extends React.Component {
constructor(props) {
super(props);
this.state = { foo: new Animated.Value(0) };
this._foo = 0;
this._onChangeFoo = this._onChangeFoo.bind(this);
}
componentDidMount() {
this.state.foo.addListener(this._onChangeFoo);
this.showFoo();
}
componentWillUnmount() {
this.state.foo.removeListener(this._onChangeFoo);
}
showFoo() {
let anim = Animated.timing(this.state.foo, { toValue: 1, duration: 1000, useNativeDriver: true });
anim.start(() => console.log(this._foo));
}
_onChangeFoo({ value }) {
this._foo = value;
}
render() {
return <View />;
}
}
【问题讨论】:
-
你试过
const foo = useState(new Animated.Value(0));吗? -
这并没有解决问题,因为我仍然需要附加监听器。这是一个范围问题。
-
我仍然不确定您要达到的目标。当然,在实例上记录一些东西显然在函数组件中不起作用,但是你想用
_foo做什么呢? -
在
useEffect中发出命令式调用。 -
我可以拥有一个包含所有
_foo的全局对象,并在卸载时清理它。感觉需要另一个钩子(或传递给useEffect的范围)。
标签: javascript reactjs react-native react-hooks