【发布时间】:2019-02-20 14:16:48
【问题描述】:
我在自定义挂钩中使用useState 挂钩。
我正在调用从useState 返回的setValue 函数两次:
1) 在 onChange 事件之后
2) 在服务器通知组件发生更改之后。
事件的流程是:
- onChange 事件(在组件中)触发
setValue= 重新渲染 - 我正在使用
useEffect(=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 };
}
【问题讨论】:
-
在某些情况下,当将相同的值传递给状态设置器时,有一些优化可以避免重新渲染,但不能保证它不会重新渲染。有关更多详细信息,请在此处查看我的答案:stackoverflow.com/questions/54715188/…
标签: reactjs react-hooks