我正在使用定义useState
的父组件来管理要在面板中显示的消息
类似这样的东西(伪代码)
const Com1 = ({message, setMessage}) => {
useEffect(() => {
const fun = async () => {
if (message) {
await wait(4000)
setMessage('')
}
}
const stillMounted = { value: true }
fun(stillMounted)
return () => (stillMounted.value = false)
}, [message])
return <Message>{message}</Message>
}
const Com2 = ({setMessage}) => {
if (condition) setMessage('important message`)
return <></>
}
const Parent = () => {
const [message, setMessage] = useState('')
return (
<>
<Com1 message={message} setMessage={setMessage} />
<Others1 />
<Others2 />
<Com2 setMessage={setMessage} />
</>
)
}
问题是我只希望重新绘制<Com1> -> <Message>
组件,但是我也确实重新绘制了<Others>
这很不幸,因为如果我在<input>
元素中写数字,那么当它重新粉刷时,我会因为数字重置为原始值而丢失我的数字
如何构造代码以避免这种情况?
在您未发布<Others>
源代码的情况下,组件渲染或重新渲染此组件内部的某个位置。
无法从外部进行管理,IFIAK。
[React确实具有控制shouldComponentUpdate
,React.memo
,React.PureComponent
之类的重新渲染的工具-因此您可以选择一个(在<Others>
内部)。
它确实有效,只要您不想重新渲染的组件在父组件之外定义
在这种情况下,此代码和框仅在<Others>
是在主要组件中定义的情况下显示此问题
如果将此组件移到外部,则不会重新渲染
https://codesandbox.io/s/laughing-swartz-ql8j2?fontsize=14&hidenavigation=1&theme=dark
((不是最简单的代码,但是在弄清正在发生的事情时,我尽可能多地复制了自己的代码)]
import React, { useState, useEffect, useRef, forwardRef } from "react";
import styled from "@emotion/styled";
export const wait = ms =>
new Promise((res, rej) => setTimeout(() => res("timed"), ms));
const useCombinedRefs = (...refs) => {
const targetRef = useRef();
useEffect(() => {
refs.forEach(ref => {
if (!ref) return;
if (typeof ref === "function") ref(targetRef.current);
else ref.current = targetRef.current;
});
}, [refs]);
return targetRef;
};
const Com1 = ({ message, setMessage }) => {
useEffect(() => {
const fun = async () => {
if (message) {
await wait(4000);
setMessage("");
}
};
const stillMounted = { value: true };
fun(stillMounted);
return () => (stillMounted.value = false);
}, [message]);
return <Message show={message ? 1 : 0}>{message}</Message>;
};
const Com2 = ({ setMessage }) => {
const test = async () => {
await wait(4000);
setMessage("important message");
};
useEffect(() => {
test();
}, []);
return <></>;
};
export default function App() {
const [message, setMessage] = useState("");
const myRef1 = useRef();
const myRef2 = useRef();
const Others = forwardRef((props, ref) => {
const innerRef = useRef();
const combinedRef = useCombinedRefs(ref, innerRef);
const write = () => (combinedRef.current.value = 3);
return <input ref={combinedRef} onClick={write} />;
});
return (
<>
<Com1 message={message} setMessage={setMessage} />
<Others ref={myRef1} />
<Others ref={myRef2} />
<Com2 setMessage={setMessage} />
</>
);
}
const Message = styled.div`
background: ${props => (props.show ? "#ababab" : "#fff0")};
width: 100%;
border-radius: 8px;
color: #fff;
padding: 10px;
margin: 10px 0px;
transition: background 0.2s ease-in;
min-height: 50px;
`;