react组件不呈现redux存储中的新数据



我正在使用react和redux,我想在react视图中更新我的计数器值,我可以控制台我的redux存储的最新状态,但它没有反映在我的react视图。

const counter = (state = 0, action) => {
console.log(action);
if(action.type == "INCREMENT")
return state + 1;
if(action.type == "DECREMENT")
return state - 1;
else 
return state; // return same state if action not identified  
}
const {createStore} = Redux;
const store = createStore(counter);
class Counter extends React.Component {
constructor() {
super();
}
render() {
return (
<div>
<div>{this.props.state.getState()}</div>
<button onClick={this.props.onIncrement} >INC</button>
<button onClick={this.props.onDecrement} >DEC</button>
</div>
);
}
}

const render = () => {
ReactDOM.render(
<Counter 
state={store} 
onIncrement={
() => store.dispatch({ type : "INCREMENT" })
}
onDecrement={
() => store.dispatch({ type : "DECREMENT" })
}
/>,
document.querySelector('#counter'));
}
store.subscribe(function() {
console.log(store.getState())
});
render();

演示

React不会在每次Javascript数据更改时自动重新渲染视图,即使您的视图绑定到该数据。

React组件仅在少数情况下重新渲染:

  1. 在组件内部调用this.setState({ ... })
  2. 重新渲染父React组件

还有一些其他方法可以强制重新渲染,但不建议使用,因为它们速度慢得多,会让你的应用程序变得迟钝。

要更正示例,请为state对象而不是props对象上的实际数据执行数据绑定。通过这种方式,React知道在计数器更改时只重新渲染组件。这在小样本中可能不是很重要,但当您希望重用组件或将其嵌入到较大的页面中时,这一点非常重要。

然后订阅您的存储,并在回调中调用setState进行任何更改。这样React就可以决定重新渲染的实际时间。

class Counter extends React.Component {
constructor(props) {
super();
this.state = {counter: 0}; // Setup initial state
this.storeUpdated = this.storeUpdated.bind(this);
props.store.subscribe(this.storeUpdated); // Subscribe to changes in the store
}
storeUpdated() {
this.setState( // This triggers a re-render
{counter: this.props.store.getState()});
}
render() {
return (
<div>
<div>{this.state.counter}</div>
<button onClick={this.props.onIncrement} >INC</button>
<button onClick={this.props.onDecrement} >DEC</button>
</div>
);
}
}

在你玩了一段时间并熟悉了Redux和React的工作方式后,我建议你看看这个库:

  • 在此处获取库:https://github.com/reactjs/react-redux
  • 请参阅http://redux.js.org/docs/basics/UsageWithReact.html有关此库的教程

这以一种比您自己手动完成所有绑定更干净的方式处理React和Redux之间的桥梁。

最新更新