我在自定义钩子中使用useState钩子。
我将调用两次从setValue返回的useState函数:
1)在onChange事件之后
2)在通知组件从服务器进行更改后。
事件的流动是:
setValue = rerenderuseEffect (=after rerender)钩子更新更改- API函数的服务器以更新服务器。setValue时,但是在这种情况下,值是相同的,因此不需要重命名。我的问题是,即使接收到的值是相同的,组件在收到更改通知后也会被重新命名。
我的代码:
增益分量
import * as React from 'react';
import { useDSPParamUpdate } from '../../../Hooks/useDSPParamUpdate';
import { ControlParamProps } from '../..';
const Gain = (props: ControlParamProps) => {
let min: number = 0;
let max: number = 0;
const { paramId, controlId } = props;
const { param, value, setValue } = useDSPParamUpdate({ controlId, paramId })
if (param && param.range && param.range.length >= 2) {
min = param.range[0];
max = param.range[1];
}
/*calls the setValue from the hook*/
const handleChange = (event: any) => {
const newValue = event.target.value;
setValue(newValue);
}
return (
<div className="gain">
{max}
<input className="dsp-action range-vertical" type="range"
min={min}
max={max}
value={value}
onChange={handleChange} />
{min}
</div>
);
}
export default Gain;useDSPParamUpdate -自定义钩子
import * as React from 'react';
import { ControlParamProps } from '../dsp';
import { dspService } from '../../core/services/dsp.service';
export function useDSPParamUpdate(props: ControlParamProps) {
const initValue = ...
const [value, setValue] = React.useState(initValue);
function updateDevice() {
// calls some API func to update the server (sends the value)
}
// subscribes to server changes
React.useEffect(() => {
// subscribrs to server notifications
let unsubscribe = dspService.subscribe((newVal) => setValue(newVal));
return () => {
unsubscribe();
};
}, []);
// sends data to the server after update
React.useEffect(() => {
updateDevice();
}, [value]);
return { param, value, setValue };
}发布于 2019-02-20 14:26:13
通常情况下,如果render()被称为额外的时间,这不是一个问题。
但是,如果需要,可以通过检查值是否相同来保护调用setValue()。
let unsubscribe = dspService.subscribe(
(newVal) =>
newVal !== value && setValue(newVal)
); 也许稍微有点迂腐,但它与componentDidUpdate中通常使用的方法是相同的
请注意,useState没有像shouldComponentUpdate那样提供任何逻辑。因此,如果您想以更声明性的方式来实现它,就必须重构您的组件才能成为基于类的PureComponent访问器。
https://stackoverflow.com/questions/54788454
复制相似问题