所以我有一个React Native应用程序,最近在其中添加了Redux。
现在,我遇到了以下问题:
有一个子组件(可以在其中设置项目高度值的数字滑块),由父组件调用。每当子组件中数字滑块的值更改时,我都希望在父组件中有console.log
个更新值。
因此,父组件必须以某种方式可以访问Redux存储,但是我不知道该怎么做。我尝试将父组件转换为Class Component并调用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所述,商店已正确更新并且可以正常工作。
能帮我吗?
答案 0 :(得分:1)
您还需要将父级连接到商店。目前,您的父母不知道商店,也没有关系。这是状态的整个还原点,灵活性和可伸缩性。
const Parent: React.FC<Props> = ({height}) => {
console.log('height', height);
};
const mapStateToProps = ({ heightResult: { height }}: RootState) => ({ height });
export default connect(mapStateToProps)(Parent);