[英]Set initial state from props in React componenet
我有這樣一個組件,我在其中從 props 設置初始狀態:
class CarsModal extends PureComponent {
constructor(props) {
super(props);
autoBind(this);
const { data } = {} } = props;
this.state = {
selectedCar: data.category || '',
cars: [],
isSpam: data.spam,
pick: data.pick,
suitable: data.suitable,
articles: false,
show: false,
};
this.messageTimer = 0;
}
async componentDidMount() {
const cars = await getCars();
this.setState({
cars,
});
}
componentWillUnmount() {
clearTimeout(this.messageTimer);
}
close() {
}
select(car) {
this.setState({
selectedCar: car,
});
}
async save(scrapeRequest = false) {
const { carId } = this.props;
const {
selectedCar,
isSpam,
pick,
suitable,
articles,
} = this.state;
await curateCar(storyId, {
selectedCar,
is_spam: isSpam,
pick: pick,
suitable: suitable,
articles: articles,
scrape: scrape,
});
if (!scrape) {
this.setState({
show: true,
});
clearTimeout(this.messageTimer);
this.messageTimer = setTimeout(() => {
this.setState({
show: false,
});
}, 1500);
}
}
scrape() {
this.save(true);
}
toggle(key) {
this.setState((state) => ({
[key]: !state[key],
}));
}
render() {
const { show, curatorData } = this.props;
const { author, cars, show } = this.state;
return (
<Modal
show={show}
onHide={this.handleClose}
dialogClassName={cx('curate-modal')}
centered
>
<ionClick={this.close} />
<h3>Tools</h3>
<div>
<span>Auto:</span>
<DropdownButton
title={(
<>
{selectedAuthor}
<i />
</>
)}
>
{cars.map((car) => (
<Dropdown.Item
key={author}
active={author === car}
onClick={() => this.select(author)}
>
{author}
</Dropdown.Item>
))}
</DropdownButton>
</div>
{OPTIONS.map((option) => (
<Option
key={option.key}
id={option.key}
checked={this.state[option.key]}
onChange={() => this.toggle(option.key)}
>
{option.content}
</Option>
))}
<div className={cx('update-info')}>
<button
type="button"
onClick={() => this.save()}
>
Update
</button>
{showMessage && (
<span>Updated</span>
)}
</div>
<hr />
<span
className={cx('link')}
onClick={this.scrape}
>
Scrape article
</span>
<a href='/'>Test 1</a>
<a href='/'>Vtest 2</a>
</Modal>
);
}
}
const mapDispatchToProps = (dispatch) => ({
actions: bindActionCreators({ ...actions }, dispatch),
});
const mapStateToProps = (state) => ({
userData: state.reducer.userData,
});
但我知道從 props 設置初始狀態是反模式。 我嘗試使用getDerivedStateFromProps(nextProps, prevState)
React 組件從 props 初始化狀態
但是在那之后我的狀態每次都會更新並且實際上並沒有改變,它是否每次都使用相同的道具更新。 我只需要在INITIAL
加載時設置初始狀態。 我怎樣才能做到這一點?
我強烈建議您不要使用 getDerivedStateFromProps。 這就是為什么 reactjs 博客有一篇名為“你可能不需要派生狀態”的帖子
我認為對於基於 props 設置初始狀態到底有什么問題(以及 props 的意義是什么)存在一些普遍的困惑。
props 的重點是它們提供了一種簡單且一致的方式來傳遞數據,並且當這些 props 發生變化時,react 會自動更新視圖。
狀態點是提供一種一致的方式來在您的應用程序中存儲“有狀態”信息(也稱為可以更改的信息)。
讓我們繪制一些示例:
(A) state (source of truth) => view
// 這很好。 真相的來源是國家。
(B) state (source of truth) => props => view
// 這很好。 真相的來源是父組件狀態。 (或者,狀態將是 redux 商店 - 也很好)
(C) redux store (source of truth) => props => state => view
// 這令人困惑。 為什么我們不直接去store => props => view
?
(D) state (source of truth) => props => state => view
// 這令人困惑。 我們現在有兩個不同狀態的真相來源。 然而,這並不一定在所有情況下都是反模式。
(E) state/store => props => state (after initial seed of data, this is the source of truth) => view
只要您僅使用上面的狀態作為數據的初始種子,這就不是反模式。 在隨后的渲染中,(E)中的信息流實際上只是state => view
。 這是簡單且單向的,具有單一的事實來源。
這篇文章可能會有所幫助。
如何在 componentDidMount 中使用 props 設置狀態?
componentDidMount(){
this.setState({
selectedCar: this.props.data.selectedCar
})
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.