简体   繁体   English

mapStateToProps 返回组件 state 而不是存储 state

[英]mapStateToProps returning component state and not store state

I've been learning how to use Redux , and I've come across a problem which I can't quite wrap my head around.我一直在学习如何使用Redux ,并且遇到了一个我无法完全解决的问题。

I'm attempting to use the native Redux connect() function in order to pass state and reducers (or dispatchers? I'm not quite 100% on the terminology yet).我正在尝试使用本机Redux connect() function 以传递 state 和reducers (或调度程序?我还不是 100% 的术语)。 And everything appeared to be working smoothly until I added an additional slice to the store.在我向商店添加一个额外的slice之前,一切似乎都在顺利进行。

This is the basic layout of my Redux app:这是我的Redux应用程序的基本布局:

playerSlice.js playerSlice.js

export const playerSlice = createSlice({
    name: "player",
    initialState: {
        stateOne: "",
        stateTwo: "",  
    },
    reducers: myReducers
});

tracksSlice.js轨道切片.js

export const tracksSlice = createSlice({
    name: "tracks",
    initialState: {
        stateThree: "" 
    },
    reducers: myReducers
});

Component.js组件.js

class Test extends Component{
    constructor(){
        super();
        this.state = {
            componentStateOne: "",
            componentStateTwo: "",
        };
    }
    // etc...
}

For some reason, when I retrieve the state from the mapStateToProps() function, I retrieve the state for the component Test , and not the state from Redux :出于某种原因,当我从mapStateToProps() function 检索 state 时,我检索了组件Test的 state,而不是Redux 的state

connect(state => {
    // this will return 
    // { componentStateOne: "", componentStateTwo: "" }
    // instead of 
    // { stateOne: "", stateTwo: "", stateThree: "" }
    console.log(state);

    return {
        // etc...
    }
})(Test);

All help is appreciated, cheers.感谢所有帮助,干杯。

I think you should change connect section of your code.我认为您应该更改代码的连接部分。 connect gets two parameters and the fist of those is mapStateToProps. connect 有两个参数,其中第一个是 mapStateToProps。

const mapStateToProps = (state) => {
      //
      return {
      
      };
    };
    
    export default connect(mapStateToProps)(Test);

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

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