如何更新 React 组件内的 map() 变量,onclick?
How to update a map() variable inside a React component, onclick?
在不重新加载页面的情况下重新呈现 map()
变量的正确方法是什么?在我的 React 应用程序中,另一个组件 Y 中的按钮需要再次 运行 组件 X 中的 map const ,因为一些它的对象和数组一直在变化。
X.jsx
import React, {component} from 'react';
class X extends Component {
render () {
return (
<button>
reload
</button>
)
}
}
Y.jsx
import React, {component} from 'react';
import myjson from './myjson.json';
const myMap = myjson.all.map((all)=>
<li>
{all.title}
</li>
);
class Y extends Component {
render () {
return (
<div>
{myMap}
</div>
)
}
}
myjson.json
{
"all"[
{"title": "firsttitle"},
{"title": "secondtitle"}
]
}
基本上要重新渲染,你需要改变状态,所以反应会自动渲染你的component.In你上面的代码,将你的 myMap 数组作为 Y 组件中的状态移动并在 Y 中创建一个处理程序并传递它作为 X 的道具并将其附加到按钮。
import React, {component} from 'react';
import X from 'components/X';// your component path here
class Y extends Component {
constructor(props){
super(props);
this.state = {
"all"[
{"title": "firsttitle"},
{"title": "secondtitle"} ]
}
}
handlerToUpdateState = ()=>{
this.setState({...update here.....})
}
render () {
return (
<div>
{myMap}
<X handler={this.handlerToUpdateState}/>
</div>
)
}
}
在不重新加载页面的情况下重新呈现 map()
变量的正确方法是什么?在我的 React 应用程序中,另一个组件 Y 中的按钮需要再次 运行 组件 X 中的 map const ,因为一些它的对象和数组一直在变化。
X.jsx
import React, {component} from 'react';
class X extends Component {
render () {
return (
<button>
reload
</button>
)
}
}
Y.jsx
import React, {component} from 'react';
import myjson from './myjson.json';
const myMap = myjson.all.map((all)=>
<li>
{all.title}
</li>
);
class Y extends Component {
render () {
return (
<div>
{myMap}
</div>
)
}
}
myjson.json
{
"all"[
{"title": "firsttitle"},
{"title": "secondtitle"}
]
}
基本上要重新渲染,你需要改变状态,所以反应会自动渲染你的component.In你上面的代码,将你的 myMap 数组作为 Y 组件中的状态移动并在 Y 中创建一个处理程序并传递它作为 X 的道具并将其附加到按钮。
import React, {component} from 'react';
import X from 'components/X';// your component path here
class Y extends Component {
constructor(props){
super(props);
this.state = {
"all"[
{"title": "firsttitle"},
{"title": "secondtitle"} ]
}
}
handlerToUpdateState = ()=>{
this.setState({...update here.....})
}
render () {
return (
<div>
{myMap}
<X handler={this.handlerToUpdateState}/>
</div>
)
}
}