几天前我已经开始学习redux,我想将它与react app结合使用,我找到了多种方法来做到这一点,但仍在寻找最好的方法。
I方法1:
首先,在正常情况下,我在类内部使用如下状态:
class myclass extends Recat.Component{
constructor(){
super()
//initiale
this.state={
something :something
}
}
//change value
this.setstate({something:something});
//use of value
this.state.something
}
在第一种情况下的问题,我不能像
useState()
useDispatch()
useSelector()
使用第一种方法,您将需要使用connect()
并调用道具来组合商店。
II方法2:
当我想使用call redux并在应用程序中使用这些hook函数时,我发现如果不删除类并将组件更改为以下格式,则无法使用它:
const Myfunction=()=>{
//to call the value from store
const something = useSelector(state=>state.somthing)
//and to use state I use usestate
const [something,setsomething] = useState(' something ');
//and of course to change value
dispatch = useDispatch();
//as a callback
dispatch(action);
}
第一个问题是为什么在第一个示例语法中钩子不起作用?
另一个问题是,将redux与react结合使用的最佳方法是什么?为什么?
提前致谢。
您的第一种方法使用一个类组件,该组件与Redux Hooks不兼容。要通过类组件与Redux交互,您需要使用connect
/ mapStateToProps
。
https://react-redux.js.org/using-react-redux/connect-mapdispatch
第二种方法使用功能组件,该组件与Redux Hooks兼容。
https://react-redux.js.org/api/hooks
确实没有“最佳”方法,但这两种方法都是完全有效的,但是React通常会朝功能组件发展,因此也倾向于这样做。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句