我正在尝试以我认为纯粹的redux
方式实现应用。将数据移出存储区而不通过道具。
在下面的示例中,我不必将道具传递给List
组件。它使用list
从存储中提取connect
。但是我看不到没有使用道具就无法将element
从商店中的list
拉到Element
组件中的任何方法。有没有一种方法可以在不通过道具的情况下完成它?
import React, { Component } from 'react';
import ReactDOM from 'react-dom'
import {createStore} from 'redux'
import thunk from 'redux-thunk'
import {connect, Provider} from 'react-redux'
//Just return the same state
const testReducer = (state=null,{list}) => ({ ...state, list })
function testAction() {
return {
type: 'TEST',
list: ['first','second']
}
}
const store = createStore(testReducer, [thunk])
store.dispatch(testAction())
class List extends Component {
render(){
const {list} = this.props
return(
<div>
{list.map((element) => {
return(<Element key={element} element={element} />)
})}
</div>
)
}
}
function mapStateToProps({list}){
return( {
list
})
}
const ConnectList = connect(mapStateToProps)(List)
class Element extends Component {
render(){
const {element} = this.props
return(
<div>{element}</div>
)
}
}
ReactDOM.render(<Provider store={store}>
<ConnectList />
</Provider>,
document.getElementById('root')
);
答案 0 :(得分:0)
这是使用Redux将道具传递到组件的正确且常见的方法。在这里,您的主要想法是在商店中保存list
个数据。您无法在商店中保存此数据中的所有项目,因此仅获取list
并通过prop将其项目映射到单独的组件中是一种好方法。
即使在Redux文档中,他们也在Todo app example中使用它。
const TodoList = ({ todos, toggleTodo }) => (
<ul>
{todos.map(todo =>
<Todo
key={todo.id}
{...todo}
onClick={() => toggleTodo(todo.id)}
/>
)}
</ul>
)
此处TodoList通过另一个组件连接到商店。因此,它将从存储中获取todos
并使用Todo
道具映射todo
组件。