我正在学习 redux,我正在尝试创建一个简单的测试应用程序,以查看是否可以将来自 redux 的 props 传递给 react 组件,但它并没有像我预期的那样工作。它自己的商店工作正常,但它没有将价值传递给我的组件,有人可以指出我的代码的问题吗?谢谢。
const randomNum=()=>{...}
const ReduxPropsTest =(props)=>(
<div>
<button onClick={()=>console.log('but this component does not have the props',props.array)}>test</button>
</div>
)
const mapStateToProps=state=>{
{array:state.reducer}
}
connect(mapStateToProps)(ReduxPropsTest)
//actions
const addItem=(array=[])=>(
{
type:'ADD_ITEM',
array,
}
)
//reducer
const reducer=(state=[],action)=>{
switch(action.type){
case 'ADD_ITEM':
return [
...state,
action.array
]
default:
return state;
}
}
//store
const store=createStore(reducer)
//create test state
store.subscribe(()=>{
const state=store.getState();
console.log('I dispatched successfully: ',state)
})
const Jsx=()=>(
<Provider store={store}>
<ReduxPropsTest/>
</Provider>
)
store.dispatch(addItem({array:randomNum()}))
store.dispatch(addItem({array:randomNum()}))
store.dispatch(addItem({array:randomNum()}))
store.dispatch(addItem({array:randomNum()}))
ReactDom.render(<Jsx/>,document.getElementById('app'))
我试图根据一些建议更正我的代码,但到目前为止我还没有工作
const randomNum=()=>{...}
const ReduxPropsTest =(props)=>(
<div>
<button onClick={()=>console.log('but this component does not have the props',props.array)}>test</button>
</div>
)
const mapStateToProps=state=>({
array:state.reducer
})
const Connected = connect(mapStateToProps)(ReduxPropsTest)
const addItem=(array=[])=>(
{
type:'ADD_ITEM',
array,
}
)
const reducer=(state=[],action)=>{
switch(action.type){
case 'ADD_ITEM':
return [
...state,
action.array
]
default:
return state;
}
}
const store=createStore(reducer)
store.subscribe(()=>{
const state=store.getState();
console.log('I dispatched successfully: ',state)
})
const Jsx=()=>(
<Provider store={store}>
<Connected/>
</Provider>
)
store.dispatch(addItem({array:randomNum()}))
store.dispatch(addItem({array:randomNum()}))
store.dispatch(addItem({array:randomNum()}))
store.dispatch(addItem({array:randomNum()}))
ReactDom.render(<Jsx/>,document.getElementById('app'))