我正在使用 React 和 Redux,我想在 React View 中更新我的计数器值,我能够控制我的 Redux 存储的最新状态,但它没有反射(reflect)在我的 React View 中。
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 数据更改时自动重新呈现 View ,即使您的 View 已绑定(bind)到该数据也是如此。
React 组件只会在少数情况下重新渲染:
- 在组件内部调用
this.setState({ ... })
- 父 React 组件被重新渲染
还有一些其他方法可以强制重新渲染,但不推荐使用它们,因为它们要慢得多并且会使您的应用运行缓慢。
要更正您的示例,请对 state
对象而不是 props
上的实际数据进行数据绑定(bind)。这样 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有关此库的教程
与您自己手动完成所有绑定(bind)相比,它以一种更简洁的方式处理 React 和 Redux 之间的桥梁。
关于javascript - react 组件不呈现来自 redux 存储的新数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37743561/