Reactjs 如何在React中从可观察数组设置新的区域设置状态?
我有一个初始数组:1、2、3、4、5,并希望向数组中的每个项添加1 代码如下所示:Reactjs 如何在React中从可观察数组设置新的区域设置状态?,reactjs,rxjs,Reactjs,Rxjs,我有一个初始数组:1、2、3、4、5,并希望向数组中的每个项添加1 代码如下所示: import React from 'react'; import { from } from 'rxjs'; import { map } from 'rxjs/operators'; class App extends React.Component { constructor(props) { super(props); this.state = {
import React from 'react';
import { from } from 'rxjs';
import { map } from 'rxjs/operators';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
fromArray: [1, 2, 3, 4, 5]
};
}
componentDidMount() {
const observable$ = from(this.state.fromArray).pipe(
map(value => ({
observable: value + 1
}))
);
this._subscription = observable$.subscribe(
result => this.setState({...result})
)
}
componentWillUnmount() {
this._subscription.unsubscribe();
}
render() {
const { fromArray } = this.state;
return (
<ul>
{
fromArray.map((item, index) => <li key={index}>{item}</li>)
}
</ul>
)
}
}
export default App;
从“React”导入React;
从'rxjs'导入{from};
从“rxjs/operators”导入{map};
类应用程序扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
fromArray:[1,2,3,4,5]
};
}
componentDidMount(){
const observable$=from(this.state.fromArray).pipe(
映射(值=>({
可观测值:值+1
}))
);
此._订阅=可观测$.subscribe(
result=>this.setState({…result})
)
}
组件将卸载(){
此._订阅。取消订阅();
}
render(){
const{fromArray}=this.state;
返回(
{
fromArray.map((项,索引)=>- {item}
)
}
)
}
}
导出默认应用程序;
但是,我只得到了列表中的初始数组
如何让它工作?是演示。这里有两个问题:
- 在
函数中,您将获得数组的更新元素(2、3、4、5、6)。但是需要将新数组本身设置为状态。这就是为什么我使用了map
reduce
- 您需要指定要设置的状态的哪一部分。不是这样:
,而是这样:result=>this.setState({…result})
newFromArray=>this.setState({fromary:newFromArray})
从“React”导入React;
从“react dom”导入react dom;
从“rxjs”导入{from};
从“rxjs/operators”导入{reduce};
类应用程序扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
fromArray:[1,2,3,4,5]
};
}
componentDidMount(){
const observable$=from(this.state.fromArray).pipe(
减少((acc,值)=>[…acc,值+1],])
);
此._subscription=observable$.subscripte(newFromArray=>{
返回此.setState({fromArray:newFromArray});
});
}
组件将卸载(){
此._订阅。取消订阅();
}
render(){
const{fromArray}=this.state;
返回(
{fromArray.map((项,索引)=>(
- {item}
))}
);
}
}
const rootElement=document.getElementById(“根”);
render(,rootElement)代码>非常感谢。除了reduce之外,还有其他方法可以实现它吗?@tesicg你可以用map(value=>value+1),toArray()替换reduce((acc,value)=>[…acc,value+1],])
。非常感谢你。