【发布时间】:2020-03-27 23:03:11
【问题描述】:
所以我有一个 React Native 应用程序,最近添加了 Redux。
现在我遇到了以下问题:
有一个由父组件调用的子组件(一个数字滑块,您可以在其中设置项目的高度值)。每次子组件中数字滑块的值发生变化时,我都希望在父组件中有一个更新值的console.log。
因此,父组件必须以某种方式访问 Redux 存储,但我不知道如何做到这一点。我尝试将父组件转换为类组件并调用store.getState();,但这只是给出了存储的初始值,根本没有更新。
所以我回到作为功能组件的父级,并在没有 Redux 的情况下实现了所需的行为,但使用了回调函数。但是当我不使用 Redux 时,我有什么用呢?将来我肯定会在这个项目中需要 Redux,因此使用它来解决这个问题会很棒。
这里是没有回调函数的代码:
Parent.tsx
imports ...
import Child from '../../atoms/Child/Child';
import store from '../../../../index.js';
const Parent: React.FC<Props> = () => {
// console.log('store: ', store.getState());
const renderChild= () => {
return (
<View>
<Child></Child>
</View>
);
};
const dataArray = [{content: renderChild()}];
return (
<Accordion
dataArray={dataArray}
/>
);
};
export default Parent;
Child.tsx
imports ...
import {connect} from 'react-redux';
import {RootState} from '../../../rootReducer/rootReducer';
import {setHeight} from '../../../store/child/actions';
import {HeightState} from '../../../store/child/types';
type Props = {};
const Child: React.FC<Props> = () => {
const [sliderValue, setSliderValue] = useState(65);
useEffect(() => {
setHeight({height: sliderValue});
}, []);
useEffect(() => {
setHeight({height: sliderValue});
}, [sliderValue]);
return (
<View>
<Text>Height is {sliderValue} inches</Text>
<Slider
step={1}
value={sliderValue}
onValueChange={sliderValue => setSliderValue(sliderValue)}
/>
</View>
);
};
function mapStateToProps(state: RootState) {
return {
height: state.heightResult.height,
};
}
const mapDispatchToProps = {
setHeight,
};
export default connect(mapStateToProps, mapDispatchToProps)(Child);
根据 Redux Devtools,商店已正确更新并且运行良好。
你能帮帮我吗?
【问题讨论】:
-
您需要用
connect包裹Parent并传递您需要的道具(为此使用mapStateToProps)
标签: reactjs react-native redux react-redux