我是菜鸟,旨在学习React Kung-Fu技术。
我正在努力实现useContext来更新来自两个同级组件的一组值
MainView.js
export function MainView() {
return(
<Fragment>
<canvas id='paper-canvas' resize='true' />
<ViewProvider>
<Sketch />
<PathControls />
</ViewProvider>
<Header />
</Fragment>
);
}
ViewContext.js
export const ViewContext = createContext([{}, () => {}]);
export const ViewProvider = (props) => {
const [isPathVisibleState, setIsPathVisibleState] = useState(true);
return(
<ViewContext.Provider value={[isPathVisibleState, setIsPathVisibleState]}>
{props.children}
</ViewContext.Provider>
);
}
PathControls.js
export default function PathControls(props) {
const [isPathVisibleState, setIsPathVisibleState] = useContext(ViewContext);
function handlePathVisibleChange() {
console.log(isPathVisibleState);
setIsPathVisibleState(isPathVisibleState => !isPathVisibleState);
}
return(
<div className='path-line-controls container fixed-bottom'>
<img src={pathLineIcon} alt='Show/Hide path line' title='Show/Hide path line' onClick={handlePathVisibleChange} />
</div>
);
}
Sketch.js
export default function Sketch(props) {
const [isPathVisibleState, setIsPathVisibleState] = useContext(ViewContext);
window.onload = function() {
// Paperjs initialization settings
paper.install(window);
paper.setup('paper-canvas');
// Creates a new path line that shows the connected dots
path = new Path();
path.strokeColor = 'black';
path.visible = isPathVisibleState;
view.onMouseDown = function(event) {
addDot(event.point);
console.log("MOUSEDOWN------","PATH:", isPathVisibleState);
}
}
function addDot(point) {
//...
}
return null;
}
我的目标是使用 PathControls 组件按钮来切换值 isPathVisibleState true / false,以便在 Sketch 组件 visible 属性切换为true / false
我当前的设置确实会从 PathControls 组件中切换 isPathVisibleState 是/否,但是当我从 Sketch 组件中管理状态变量时,它总是保持在Context组件中设置的相同初始值。
任何帮助将不胜感激。
答案 0 :(得分:0)
似乎Sketch
不会重新渲染所有isPathVisibleState
的更改,请尝试使用useEffect
添加副作用:
export default function Sketch(props) {
const [isPathVisibleState, setIsPathVisibleState] = useContext(ViewContext);
useEffect(() => {
window.onload = function() {
// Paperjs initialization settings
paper.install(window);
paper.setup("paper-canvas");
// Creates a new path line that shows the connected dots
path = new Path();
path.strokeColor = "black";
};
}, []);
useEffect(() => {
path.visible = isPathVisibleState;
view.onMouseDown = function(event) {
addDot(event.point);
console.log("MOUSEDOWN------", "PATH:", isPathVisibleState);
};
}, [isPathVisibleState]);
function addDot(point) {
//...
}
return null;
}
请注意,当您现在编写代码时,Sketch
主体将在每次重新渲染时执行,这就是为什么我在第一个componentDidMount
中将其移至useEffect
循环的原因。 / p>
如果它不起作用,则应检查为什么Sketch
不重新渲染,将沙箱添加到它总是一个好步骤。