我是redux的新手,我正在尝试在我的react应用程序中实现一个小的概念。 我已经收到来自调度和订阅中的数据。如何将订阅数据打印到UI。下面的代码不起作用,错误在哪里以及如何解决。
import React, { Component } from 'react';
import { createStore } from 'redux';
export default class App1 extends Component {
render() {
const initalState={items:
[{
name:"test"
}]
};
// Create Reducer, this is need state and action
const reducer = function(state,action){
if(action.type==='POST'){
return action.payload;
}
return state;
}
// Create store, this is need reducer and state
const store=createStore(reducer,initalState);
// Subscribe
store.subscribe(()=>{
items: store.getState().items;
});
// Dispatch
store.dispatch({
type:"POST",
payload:{
items:
[{
name:"test 1"
},
{
name:"test 2"
}]
}
});
return (
<div>
{this.props.items.map((item) => <p> {item.name} </p> )}
</div>
)
}
}
答案 0 :(得分:1)
我对您的代码做了一些更改,并创建了jsfiddle,以便更好地理解。
简而言之,当您使用 class 时,应在 componentDidMount 或某些事件(而不是 render 方法)中调度动作。其次,在状态更改后,我使用this.forceUpdate();
重新渲染组件。
我认为您将基于类的组件和基于功能的组件弄混了。
这里是完整的工作示例,而工作的jsfiddle是here:
const initalState={
items: [{
name:"test"
}]
};
// Create Reducer, this is need state and action
const reducer = function(state,action){
if(action.type==='POST'){
return action.payload;
}
return state;
}
// Create store, this is need reducer and state
const store=Redux.createStore(reducer,initalState);
class App1 extends React.Component {
componentDidMount () {
// subscribe
store.subscribe(()=>{
this.forceUpdate(); // actually triggers component to rerender on subscribe. Note you can also use this.setState() to trigger changes
});
// Dispatch
store.dispatch({
type:"POST",
payload: {
items: [
{
name:"test 1"
},
{
name:"test 2"
}
]
}
});
}
render() {
return (
store.getState().items.length > 0 &&
<div>
{store.getState().items.map((item) => <p> {item.name} </p> )}
</div>
)
}
}
ReactDOM.render(
<App1 />,
document.getElementById('container')
);