Reactjs 使用useReducer使分离的组件消失
我目前正在学习React Hooks功能,因此我创建了一个小实验,如果单击按钮,将出现一个不可见的挂载框;如果该框可见,并且您单击页面上除该框以外的任何位置,则该框将消失。我正在努力让这个盒子消失,我不知道是什么导致了这个错误 初始状态和减速器: 长方体组件: 主要内容:Reactjs 使用useReducer使分离的组件消失,reactjs,react-hooks,Reactjs,React Hooks,我目前正在学习React Hooks功能,因此我创建了一个小实验,如果单击按钮,将出现一个不可见的挂载框;如果该框可见,并且您单击页面上除该框以外的任何位置,则该框将消失。我正在努力让这个盒子消失,我不知道是什么导致了这个错误 初始状态和减速器: 长方体组件: 主要内容: 您正在使用两个useReducer实例,而您只需要在应用程序组件级别拥有一个实例,并将dispatch作为道具传递给Box,否则您将只更新框中useReducer使用的状态,而不更新应用程序组件中的状态 function Ap
您正在使用两个useReducer实例,而您只需要在应用程序组件级别拥有一个实例,并将dispatch作为道具传递给Box,否则您将只更新框中useReducer使用的状态,而不更新应用程序组件中的状态
function App() {
const [state, dispatch] = useReducer(reducer, initialState);
function showBox() {
dispatch({ type: 'show' });
}
return (
<section>
{ state.visible && <Box dispatch={dispatch}/> }
<button onClick={showBox}>Show box</button>
</section>
)
}
Box.js
function Box({dispatch}) {
const boxElement = useRef(null);
const boxStyle = {
width: '200px',
height: '200px',
background: 'blue'
};
function hideBox(e) {
if(!boxElement.current.contains(e.target)) {
dispatch({ type: 'hide' });
}
}
useEffect(() => {
window.addEventListener('click', hideBox);
return () => {
window.removeEventListener('click', hideBox);
}
});
return <div style={boxStyle} ref={boxElement} />
}
谢谢非常有用的提示。那么,祖先组件应该始终是分派的源?@jstarnate是的,就像使用redux时存储全局一样,这里的reducer概念也是一样,需要共享reducer状态的组件需要访问相同的reducer
function App() {
const [state, dispatch] = useReducer(reducer, initialState);
function showBox() {
dispatch({ type: 'show' });
}
return (
<section>
{ state.visible && <Box /> }
<button onClick={showBox}>Show box</button>
</section>
)
}
function App() {
const [state, dispatch] = useReducer(reducer, initialState);
function showBox() {
dispatch({ type: 'show' });
}
return (
<section>
{ state.visible && <Box dispatch={dispatch}/> }
<button onClick={showBox}>Show box</button>
</section>
)
}
function Box({dispatch}) {
const boxElement = useRef(null);
const boxStyle = {
width: '200px',
height: '200px',
background: 'blue'
};
function hideBox(e) {
if(!boxElement.current.contains(e.target)) {
dispatch({ type: 'hide' });
}
}
useEffect(() => {
window.addEventListener('click', hideBox);
return () => {
window.removeEventListener('click', hideBox);
}
});
return <div style={boxStyle} ref={boxElement} />
}