本节知识点
- (1) 无状态组件和有状态组件的区别
- (2) 无状态组件的使用
(一)无状态组件和有状态组件的区别
(1)传统组件都会有钩子函数,生命周期函数等等比如
import React, { Component } from 'react'
import store from './store/index'
import * as actions from './store/actions'
import Listdo from './Listdo'
class App extends Component {
constructor(props) {
super(props)
this.state = store.getState()
store.subscribe(this.changeStore.bind(this))
}
render() {
return (
<Listdo
message={this.state.message}
list={this.state.list}
changeValue={this.changeValue.bind(this)}
changeStore={this.changeStore.bind(this)}
changelist={this.changelist.bind(this)}
deleteone={this.deleteone.bind(this)}
/>
)
}
componentDidMount() {
store.dispatch(actions.get_data())
}
changeValue(e) {
let value = e.target.value
store.dispatch(actions.change_value(value))
}
changelist() {
store.dispatch(actions.change_list())
}
changeStore() {
this.setState(store.getState())
}
deleteone(index) {
store.dispatch(actions.delete_one(index))
}
}
export default App
(2) 而无状态组件没有这些,因为里面没有逻辑没有方法只有UI展示,所以他不用继承那些个类,只是暴露个方法即可
方法传递都需要通过props
import React, { Fragment } from 'react'
const Todolist = props => {
return (
<Fragment>
<input type="text" value={props.message} onChange={props.changeValue} />
<button onClick={props.changelist}>提交</button>
<ul>
{props.list.map((item, index) => {
return (
<li
key={index}
onClick={() => {
props.deleteone(index)
}}
>
<span>第{index}个+++</span>
<span>{item}</span>
</li>
)
})}
</ul>
</Fragment>
)
}
export default Todolist
网友评论