gpt4 book ai didi

reactjs - redux 和 react 连接不起作用?

转载 作者:行者123 更新时间:2023-12-04 14:24:48 26 4
gpt4 key购买 nike

<分区>

我正在学习 redux,我正在尝试创建一个简单的测试应用程序,看看我是否可以将 props 从 redux 传递给 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'))

这是我的问题的图片 enter image description here

我尝试根据一些建议更正我的代码,但到目前为止我没有任何效果

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'))

这是错误的图片 enter image description here

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com