简体   繁体   English

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

[英]I can't access the redux store properly in react components

I am just started using redux in my react app and I have successfully added some values on my redux store.On the same component where dispatching happens I can access the store via我刚刚开始在我的 react 应用程序中使用 redux,并且我已经成功地在我的 redux 商店中添加了一些值。在发生分派的同一个组件上,我可以通过以下方式访问商店

    store.getState();

but on other components I can't access it by mapStateToProps or the above method.但在其他组件上,我无法通过 mapStateToProps 或上述方法访问它。 I really need to why this happens.我真的需要知道为什么会发生这种情况。

index.js索引.js

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

store.js商店.js

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

reducer.js减速器.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动作.js

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

login.js登录.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另一个页面.js

export default function AnPage() {

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

console output at reducer.js 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)-> console.log(this.props.state)->

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

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

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

I have edited the question.我已经编辑了这个问题。

You shouldnt declare the state again in the constructor .您不应在构造函数中再次声明状态。 You will get the state from the props using the mapStateToProps method.您将使用 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);
     }

I have found out that the reason for the initial values of state as output on other components was due to the fact that I was refreshing the page each time a new component was loaded.Since redux states have a special behaviour of wiping the state on refresh as I found in this stack I have to add 'Link' from react-router-dom to avoid refreshing and used redux-persist library to load the state if refreshed for other reasons.我发现将 state 的初始值作为其他组件输出的原因是因为每次加载新组件时我都会刷新页面。因为 redux 状态具有在刷新时擦除状态的特殊行为正如我在此堆栈中发现的那样,我必须从 react-router-dom 添加“链接”以避免刷新并使用 redux-persist 库加载状态(如果因其他原因刷新)。

I hope this will be helpful for someone who comes across on these kind of issues.我希望这对遇到此类问题的人有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM