通过React Redux使用Selector Hook作为道具



Precursor:我对Redux还很陌生,但我对编码有足够的了解,我知道下面的解决方案并不理想。虽然它有效,但我真的不确定是否使用eval((并将钩子作为字符串传递。我想看看是否有更好的方法来做到这一点,或者React Redux是否有我想要实现的内置功能。

场景:下面代码中我的所有ChildComponents都是通用组件(下拉列表等(,不应该包括将它们链接到特定项目的代码;我尽量保持它们的通用性。然而,当checkBox1触发调度以更改存储中的Item1时,我只希望重新发送预期的Dropdown(dropdown2(,而不是整个ParentComponent(以及扩展到所有子级(。我还希望dropdown2每次在商店中更改Item1时都更新它的选项。我唯一能想到的方法是在不需要重新提交整个ParentComponent的情况下,在子级中部署useSelector钩子。不过,我不想在子级中显式声明钩子,因为这违反了抽象,并迫使我将变通方法代码放在通用的Dropdown组件中。

旁注:我已经考虑了如何在Parent中声明useSelector并防止它强制重新发布,但道具仍然必须在dropdown2上更改,这仍然会强制Parent的重新发布以反映dropdown2的新道具。

const ParentComponent = () => {
let passSelector = "selector(state => state.Item1 ? state.Item2.concat(state.Item3) : state.Item2)";
let dropdown1 = <Dropdown input={[thing1, thing2]} />;
let dropdown2 = <Dropdown input={passSelector} />
let checkbox1 = <Checkbox onClick={() => dispatch(toggleItem1)} />;
let menu1 = [dropdown1];
let menu2 = [dropdown2, checkbox1];
return (
<div>
<Checkbox1 onClick={doThing} />
<Switch onSwitch={switchyThing} />
{mode &&
menu1
}
{!mode &&
menu2
}
<div/>
);
}
const Dropdown = ({input}) => {
const selector = useSelector; // Grabbed from the import statements to force importation.
const options = (typeof input === 'string') ? eval(input) : input;
... some other code ...
return (
{options && options.map(option => {
...do thing with option...
}
);
}   

您可能只将要用作选择器的函数从父级传递给子级,而不是字符串。像这样的东西?

const ParentComponent = () => {
const selector = state => state.Item1 ? [...state.Item2, ...state.Item3] : state.Item2;
return (
<div>
<Dropdown selector={selector} />
<div/>
);
}
const Dropdown = ({selector}) => {
const options = useSelector(selector);
//... some other code ...
return (
{options && options.map(option => {
//...do thing with option...
}
);
}   

最新更新