Redux:如何将ID传递给mapStateToProps函数以从具有该ID的实体获取状态

时间:2018-01-06 11:28:02

标签: reactjs redux react-redux

我有这个容器组件:

const TodoListContainer = connect(mapStateToProps, mapDispatchToProps)(TodoListComponent)

我这样称呼它:

    let TodoListHtml = document.getElementById('TodoList');

    render(
        <Provider store={store}>
            <TodoListContainer id={TodoListHtml.dataset.id}/>
        </Provider>,
        TodoListHtml
    )

正如您所看到的,我向容器传递了id=TodoListHtml.dataset.id,它是我想要呈现的列表的ID。

我的state就是这样形成的:

state {
    TodoLists: {
        entities: {
            1: {
                id: 1,
                name: 'The name of the list'
            }
        }
    }
}

所以,我的容器组件应该来自state TodoList state.TodoLists.entities.1

我的伪代码:

// Container.js
const getTodoList = (state, id) => {
    return state.TodoLists.entities.1
}

const mapStateToProps = (state, id) => {
    return {
        todoList: getTodoList(state, id)
    }
}

export default const TodoListContainer = connect(mapStateToProps)(TodoListComponent)

这是呈现容器组件的代码

// Todolist.html: The html calling the container component
let TodoListHtml = document.getElementById('TodoList');

render(
    <Provider store={store}>
        <TodoListContainer id={TodoListHtml.dataset.id}/>
    </Provider>,
    TodoListHtml
)

问题是:我该如何传递ID?

1 个答案:

答案 0 :(得分:3)

MapStateToPropsownProps作为第二个参数,你可以将id传递给Container组件然后你就像

那样
const mapStateToProps = (state, ownProps) => {
    return {
        todoList: getTodoList(state, ownProps.id)
    }
}