作者steven11329 (清新柳橙)
看板Ajax
标题Re: [问题] redux + react 改state的值
时间Sat Nov 4 22:29:09 2017
setState 会触发 state update,
因此 render() 会再被叫起来,
你需要的是在 Switch class 里加上 shouldComponentUpdate(nextProps, nextState)
根据 React life cycle 这 function 会在 render() 之前决定是否真的要re-render。
retrun true 就是要re-render
以下是程式码
class Button extends React.Component {
render() {
return <div className="btn">button</div>
}
}
class Switch extends React.Component {
constructor(props) {
super(props);
this.state = store.getState().data[this.props.index];
}
//-----加入这块-----
shouldComponentUpdate(nextProps, nextState) {
if (this.state.on === nextState.on) {
return false;
}
return true;
}
/-----加入这块-----
render() {
console.log(`update: switch-${this.props.index}`);
return <div
className={"switch" + (this.state.on ? " switch-on" : "")}
onClick={this.update.bind(this)}
>
<Button />
</div>;
}
update() {
store.dispatch({
type: "ChangeSwitch",
num: this.props.index
});
}
refresh() {
this.setState(store.getState().data[this.props.index]);
}
componentDidMount() {
this.unsubscribe = store.subscribe(this.refresh.bind(this));
}
componentWillUnmount() {
this.unsubscribe();
}
}
let reducer = function (state, action) {
console.log(state);
console.log(action);
switch (action.type) {
case "ChangeSwitch":
let newData = state.data.map((obj, i) => {
if (i === parseInt(action.num)) {
return { on: !obj.on };
} else {
return obj;
}
});
console.log(state.data);
console.log(newData);
return Object.assign({ data: newData });
default:
return state;
}
};
let store = createStore(reducer, {
data: [{ on: false }, { on: true }, { on: true }]
});
ReactDOM.render(<Switch index="0" />, document.getElementById("switch-0"));
ReactDOM.render(<Switch index="1" />, document.getElementById("switch-1"));
ReactDOM.render(<Switch index="2" />, document.getElementById("switch-2"));
另外 Redux 在配合 React上有 react-redux package 可以用。
参考教学:
http://redux.js.org/docs/basics/UsageWithReact.html
写得算简单但是要看懂还是要花点时间。
差别在於你可以不用一直设定setState它是透过props来传递。
以上。
--
人生宗旨:摔不死!那就再来吧!
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 114.45.10.203
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/Ajax/M.1509805757.A.D6D.html
1F:推 nvizero: 感谢你 11/06 21:16