3 回答

手动清除可以,但是比较麻烦,需要手写action,然后在每个reducer中监听。
如果想通用一点,可以先建个action
// keys 为state的keyexport function clearState(...keys) {return {type: CLEAR_STATE,keys: keys};}
3.然后写个高阶组件
import React, {PropTypes, Component} from 'react';import {clearState} from 'actions';import {connect} from 'react-redux';const clearStateWithUnmount = (...stateKeys) => WrappedComponent => {if(!stateKeys) {return;}let instance = class extends Component {componentWillUnmount() {this.props.dispatch(clearState(...stateKeys));}render() {return <WrappedComponent {...this.props}/>;}};return connect(null)(instance);};export default ClearStateWithUnmount;
4.在创建store时,处理一下
// 这里引入所有reducerconst appReducer = combineReducers({...reducers});const rootReducer = (state, action) => {// 清除指定的stateif(action.type === CLEAR_STATE) {const {type, keys} = action;keys.forEach(k => {_.set(state, k, undefined);//_.set方法为lodash中的方法,这里将对应的state设为undefined});}return appReducer(state, action);};//创建storeconst store = createStore(rootReducer);
5.大功告成,比如有个user组件
//这里使用装饰器模式,需要babel支持@clearStateWithUnmount('user')class User extends Component{...}//如果不想用装饰器,可以用一般的写法clearStateWithUnmount('user')(User)
6.这样在User组件unmount时候,就清除了相应的store
7.如果你的state有深层嵌套,比如{user: {name: 'foo', age: 12}},这里也同样支持@clearStateWithUnmount('user.name', 'user.age')
8.如果不想侵入现有项目,可以做个中间件,原理是一样的

import React from 'react'
import { render } from 'react-dom'
const About = React.createClass({/*...*/})
const Inbox = React.createClass({/*...*/})
const Home = React.createClass({/*...*/})
const App = React.createClass({
getInitialState() {
return {
route: window.location.hash.substr(1)
}
},
componentDidMount() {
window.addEventListener('hashchange', () => {
this.setState({
route: window.location.hash.substr(1)
})
})
},
render() {
let Child
switch (this.state.route) {
case '/about': Child = About; break;
case '/inbox': Child = Inbox; break;
default: Child = Home;
}
return (
App
About
Inbox
)
}
})
render(, document.body)

有两种办法可以删除表中的所有数据: 1、TRUNCATE TABLE 删除表中的所有行,而不记录单个行删除操作。 语法 TRUNCATE TABLE name 参数 name 是要截断的表的名称或要删除其全部行的表的名称。 2、Delete from tablename where 1=1
添加回答
举报