import React from 'react';
import store from '../redux/store';
import { connect } from 'react-redux'
const Home = (props) => {
const [state, setstate] = React.useState(store.getState());
React.useEffect(() => {
store.subscribe(() => {
console.log("打印1", props.reduxState); // 无法获取
console.log("打印2", store.getState()); // 以这种方式可以获取
setstate(store.getState())
})
}, [])
return (
<div>
Home组件
{
state.isShow ? <div>我是否展示跟isShow有关</div> : ""
}
</div>
);
}
export default connect(state => ({
reduxState: state
}))(Home);
在React.useEffect()中,当处于subscribe订阅回调函数中,是无法通过props.reduxState获取状态的,默认获取到是就是原先在reducer的初始值;
第二种场景,在该组件有一函数用来获取props.reduxState,如果该函数被本组件调用,那么它可以获取到,如果该函数传递给子组件,那么就无法获取
function getReduxState() {
// 该函数本组件元素调用
console.log(props.reduxState) // 成功获取
}
function getReduxStateForSun() {
// 该函数通过props传递给个组件调用
console.log(props.reduxState) // 无法获取,将是reducer初始值
}
如果通过Effect的依赖项来获取更新后的reduxState,确实可以,那么如果存在功能是通过子组件调用或订阅获取reduxState,那么将如何解决这个问题?
我真正想知道的是,为什么在这两种场景下获取不到reduxState