下面是两个 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 />;
}
}
最佳答案
useRef
hook 不仅适用于 DOM 引用,还可以存储您喜欢的任何可变值。
示例
function FunctionalBar(props) {
const [foo] = useState(new Animated.Value(0));
const _foo = useRef(0);
function showFoo() {
let anim = Animated.timing(foo, { toValue: 1, duration: 1000, useNativeDriver: true });
anim.start(() => console.log(_foo.current));
}
useEffect(() => {
function _onChangeFoo({ value }) {
_foo.current = value;
}
foo.addListener(_onChangeFoo);
showFoo();
return () => foo.removeListener(_onChangeFoo);
}, []);
return <View />;
}
关于javascript - 在功能组件中存储非状态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53146575/