我无法在React组件中正确访问Redux存储

时间:2020-02-11 08:38:14

标签: javascript reactjs redux redux-store

我刚开始在我的react应用中使用redux,并且已经在redux存储中成功添加了一些值。在发生调度的同一组件上,我可以通过

访问存储
    store.getState();

,但是在其他组件上,我无法通过mapStateToProps或上述方法访问它。我真的需要知道为什么会这样。

index.js

const rootElement = document.getElementById("root");
ReactDOM.render(
<Provider store={store} > <App /> </Provider>, rootElement);

store.js

import { createStore } from "redux";
import rootReducer from "../reducers/index";
const store = createStore(rootReducer);
export default store;

reducer.js

const initialState = {
 token:"",email:"",uid:""
};

function userReducer(state = initialState, action) {
console.log("check ", state, action);

switch(action.type) {
    case "ADD_USER":
        return Object.assign({}, state, {
            token : action.token,
            email : action.email,
            uid : action.uid
        });
    default : return state;
}

}

export default userReducer;

action.js

const addUser = (token,email,uid) => ({
type:"ADD_USER",token:token,email : email,uid:uid    
})
export default addUser;  

login.js

function mapDispatchToProps  (dispatch) {
console.log(dispatch);
return { addUser : (token,email,uid)=>  dispatch(addUser(token,email,uid))
};}
class Sample extends React.Component {
constructor(props){
  super(props);
  this.state = {...........}
 }
 componentDidMount() {  

 let token = localStorage.getItem("myToken");
 let user = decode(token);
 let uid = user.id;
 let email = user.email;
this.props.addUser(token,email,uid);
console.log(this.props.state);
console.log(store.getState());
}
}
const mapStateToProps = state => {
return {state:state}
}

export default connect(mapStateToProps,mapDispatchToProps)(Sample);

anotherPage.js

export default function AnPage() {

const Data = useSelector(state=>state.userReducer);
useEffect(()=> {
somFunct(); },[]);
}
someFunct=() => {
console.log(Data) =>output is ({token: "", email: "", uid: ""})
return(
)
}

reducer.js上的控制台输出

check  {token: "", email: "", uid: ""}token: ""email: ""uid: ""__proto__: Object {type: "ADD_USER", 
token: "*******", email: "dfgsdhf@gmail.com", uid: 6264}

console.log(this.props.state)->

userReducer: {token: "", email: "", uid: ""}
__proto__: Object

console.log(store.getState())->

userReducer: {token: "*******", email: "dfgsdhf@gmail.com", uid: 6234}
__proto__: Object

我已经编辑了问题。

2 个答案:

答案 0 :(得分:0)

您不应在构造函数中再次声明状态。您将使用mapStateToProps方法从道具中获取状态。

      export const mapStateToProps = function(state) {
  return {
    token: state.token,
    email: state.email,
    uid: state.uid
  };
};

  class Sample extends React.Component {
    constructor(props){
      super(props);
     }

答案 1 :(得分:0)

我发现在其他组件上输出state的初始值的原因是由于我每次加载新组件时都会刷新页面的事实。由于redux状态具有擦拭该组件的特殊行为。刷新时的状态as I found in this stack我必须从react-router-dom添加'Link'以避免刷新,并且如果由于其他原因而刷新,则使用redux-persist库来加载状态。

我希望这会对遇到此类问题的人有所帮助。