Reactjs 子组件未更新父组件';React.js功能组件中的s状态
我有一个呈现子组件的组件。子组件管理自己的状态,我尝试使用回调将更新后的状态传递给父组件,但没有成功。我花了好几个小时试图找出这个问题,但一直没能解决。我的父组件是(不带导入): 我不理解这个警告,我确实有一系列依赖项。除此之外,selectionIsVisible:true(在“显示选择”操作中)有效,但selectionIsVisible:false(在“记录选择”操作中)有效Reactjs 子组件未更新父组件';React.js功能组件中的s状态,reactjs,Reactjs,我有一个呈现子组件的组件。子组件管理自己的状态,我尝试使用回调将更新后的状态传递给父组件,但没有成功。我花了好几个小时试图找出这个问题,但一直没能解决。我的父组件是(不带导入): 我不理解这个警告,我确实有一系列依赖项。除此之外,selectionIsVisible:true(在“显示选择”操作中)有效,但selectionIsVisible:false(在“记录选择”操作中)有效 有人能帮我吗?我很沮丧。因为把[]放错地方了。只需如下更新: const getCategoryState =
有人能帮我吗?我很沮丧。因为把
[]
放错地方了。只需如下更新:
const getCategoryState = useCallback((category) => {
dispatch({
action: "SET_CATEGORY",
category: category,
});
}, []);
谢谢越南!!!不幸的是,状态仍然没有得到更新:/
const selectionReducer = (state, action) => {
switch (action.type) {
case 'DISPLAY_SELECTION':
return {
...state,
selectionIsVisible: true
};
case 'LOG_SELECTION':
return {
...state,
category: action.category,
selectionIsVisible: false
}
default:
return state;
}
};
function CategoryOne(props) {
const [selectionState, dispatch] = useReducer(selectionReducer, {});
const { category } = selectionState;
const { sendState } = props;
useEffect(() => {
sendState(category);
}, [category, sendState])
const displaySelectionHandler = event => {
dispatch({
type: 'DISPLAY_SELECTION'
});
};
const selectCategoryHandler = event => {
dispatch({
type: 'LOG_SELECTION',
category: event.target.id
});
};
return (
<>
<div className="container">
<div className={`options-container ${selectionState.selectionIsVisible && 'active'}`}>
<div className="option">
<input className="radio" type="radio" id="One" name="category" onChange={selectCategoryHandler} />
</div>
<div className="option">
<input className="radio" type="radio" id="Two" name="category" onChange={selectCategoryHandler} />
</div>
<div className="option">
<input className="radio" type="radio" id="Three" name="category" onChange={selectCategoryHandler} />
</div>
<div className="option">
<input className="radio" type="radio" id="Four" name="category" onChange={selectCategoryHandler} />
</div>
</div>
<div className="selected" id="category" onClick={displaySelectionHandler}>
Category
</div>
</div>
</>
);
};
export default CategoryOne;
React Hook useCallback does nothing when called with only one argument. Did you forget to pass an array of dependencies?
const getCategoryState = useCallback((category) => {
dispatch({
action: "SET_CATEGORY",
category: category,
});
}, []);