map 및 join을 사용하여 반응 구성 요소를 렌더링하는 방법
String Array를 표시 할 구성 요소가 하나 있습니다. 코드는 다음과 같습니다.
React.createClass({
render() {
<div>
this.props.data.map(t => <span>t</span>)
</div>
}
})
완벽하게 잘 작동합니다. ie if props.data = [ 'tom', 'jason', 'chris'] 페이지에서 렌더링 된 결과는 tomjasonchris입니다.
그런 다음 쉼표를 사용하여 모든 이름을 결합하고 싶으므로 코드를 다음과 같이 변경합니다.
this.props.data.map(t => <span>t</span>).join(', ')
그러나 렌더링 된 결과는 [Object], [Object], [Object]입니다.
렌더링 할 반응 구성 요소가되도록 객체를 해석하는 방법을 모르겠습니다. 어떠한 제안 ?
간단한 해결책은 reduce()
두 번째 인수없이 이전 결과를 퍼 뜨리지 않고 사용 하는 것입니다.
class List extends React.Component {
render() {
<div>
{this.props.data
.map(t => <span>{t}</span>)
.reduce((prev, curr) => [prev, ', ', curr])}
</div>
}
}
두 번째 인수없이 reduce()
것 인덱스 1에서 시작 하는 대신 0, 중첩 된 배열을 완벽하게 행복하다 반응한다.
주석에서 말했듯이 reduce()
두 번째 인수가 없으면 빈 배열이 발생 하기 때문에 하나 이상의 항목이있는 배열에만 이것을 사용하고 싶습니다 . 어쨌든 빈 배열에 대해 'this is empty'와 같은 사용자 지정 메시지를 표시하고 싶기 때문에 일반적으로 이것은 문제가되지 않습니다.
Typescript 업데이트
type-unsafe없이 Typescript any
에서 React.ReactNode
유형 매개 변수를 사용하여 사용할 수 있습니다 .map()
.
class List extends React.Component {
render() {
<div>
{this.props.data
.map<React.ReactNode>(t => <span>{t}</span>)
.reduce((prev, curr) => [prev, ', ', curr])}
</div>
}
}
reduce
배열의 여러 요소를 결합하는 데 사용할 수 있습니다 .
React.createClass({
render() {
<div>
this.props.data
.map(t => <span>t</span>)
.reduce((accu, elem) => {
return accu === null ? [elem] : [...accu, ',', elem]
}, null)
</div>
}
})
이는 누산기를 null로 초기화하므로 배열의 첫 번째 항목을 래핑 할 수 있습니다. 배열의 각 다음 요소에 대해를 사용하여 이전 요소를 모두 포함하는 새 배열을 생성 ...-operator
하고 구분 기호를 추가 한 다음 다음 요소를 추가합니다.
React 16으로 업데이트 : 이제 문자열을 직접 렌더링 할 수 있으므로 쓸모없는 <span>
태그를 모두 제거하여 코드를 단순화 할 수 있습니다 .
const List = ({data}) => data.reduce((prev, curr) => [prev, ', ', curr])
<span>{t}</span>
당신이 반환하는 객체가 아닌 문자열입니다. 그것에 대한 반응 문서를 확인하십시오 https://facebook.github.io/react/docs/jsx-in-depth.html#the-transform
.join()
에서 반환 된 배열을 사용 map
하면 객체 배열을 결합하게됩니다.[object Object], ...
안에 쉼표를 넣어 <span></span>
원하는 방식으로 렌더링되도록 할 수 있습니다 .
render() {
return (
<div>
{ this.props.data.map(
(t,i) => <span>{t}{ this.props.data.length - 1 === i ? '' : ','} </span>
)
}
</div>
)
}
샘플 : https://jsbin.com/xomopahalo/edit?html,js,output
허용되는 대답은 prev
매번 배열이기 때문에 실제로 배열 배열을 반환합니다 . React는이 작업을 수행 할 수있을만큼 똑똑하지만 맵의 각 결과에 키를 부여 할 때 Reacts diffing 알고리즘을 깨는 등 향후 문제를 일으키는 경향이 있습니다.
새로운 React.Fragment
기능을 통해 근본적인 문제없이 이해하기 쉬운 방식으로이를 수행 할 수 있습니다.
class List extends React.Component {
render() {
<div>
{this.props.data
.map((t, index) =>
<React.Fragment key={index}>
<span> {t}</span> ,
</React.Fragment>
)
</div>
}
}
함께 React.Fragment
우리는 간단하게 분리 배치 할 수 있습니다 ,
반환 된 HTML의 외부 불평하지 않습니다 반응한다.
내 변형 :
{this.props.data
.map(item => <span>{item}</span>)
.map((item, index) => [index > 0 && ', ', item ])}
중첩 배열을 사용하여 ","를 외부에 보관하십시오.
<div>
{this.props.data.map((element, index) => index == this.props.data.length - 1 ? <span key={index}>{element}</span> : [<span key={index}>{element}</span>, ", "])}
</div>
데이터를 배열에 저장하고 마지막 요소를 항상 확인하는 대신 마지막 요소를 수정하여 최적화하십시오.
let processedData = this.props.data.map((element, index) => [<span key={index}>{element}</span>, ", "])
processedData [this.props.data.length - 1].pop()
<div>
{processedData}
</div>
If I just want to render a comma-separated array of components, I usually find reduce
too verbose. A shorter solution in such cases is
{arr.map((item, index) => (
<Fragment key={item.id}>
{index > 0 && ', '}
<Item {...item} />
</Fragment>
))}
{index > 0 && ', '}
will render a comma followed by a space in front of all array items except the first one.
If you want to separate the second-to-last item and the last one by something else, say the string ' and '
, you can replace {index > 0 && ', '}
with
{index > 0 && index !== arr.length - 1 && ', '}
{index === arr.length - 1 && ' and '}
This worked for me:
{data.map( ( item, i ) => {
return (
<span key={i}>{item.propery}</span>
)
} ).reduce( ( prev, curr ) => [ prev, ', ', curr ] )}
As mentioned by Pith, React 16 allow you to use strings directly so wrapping the strings in span tags are no longer needed. Building on Maarten's answer, if you also want to deal with a custom message right away (and avoid throwing an error on empty array), you could lead the operation with a ternary if statement on the length property on the array. That could look something like this:
class List extends React.Component {
const { data } = this.props;
render() {
<div>
{data.length
? data.reduce((prev, curr) => [prev, ', ', curr])
: 'No data in the array'
}
</div>
}
}
This should return a flat array. Handle s case with non iterable first object by providing an initial empty array and filters the not needed first comma from the outcome
[{}, 'b', 'c'].reduce((prev, curr) => [...prev, ', ', curr], []).splice(1) // => [{}, 'b', 'c']
Using es6 you could do something like:
const joinComponents = (accumulator, current) => [
...accumulator,
accumulator.length ? ', ' : '',
current
]
And then run:
listComponents
.map(item => <span key={item.id}> {item.t} </span>)
.reduce(joinComponents, [])
Am I the only who thinks there's a lot of needless spreading and nesting going on in the answers here? Points for being concise, sure, but it leaves the door open to issues of scale or React changing how they deal with nested arrays/Fragments.
const joinJsxArray = (arr, joinWith) => {
if (!arr || arr.length < 2) { return arr; }
const out = [arr[0]];
for (let i = 1; i < arr.length; i += 1) {
out.push(joinWith, arr[i]);
}
return out;
};
// render()
<div>
{joinJsxArray(this.props.data.map(t => <span>t</span>), ', ')}
</div>
One array, no nesting. No sexy method chaining either, but if you find yourself doing this often you can always add it to the array prototype or wrap it in a function that takes a mapping callback as well to do it all in one go.
function YourComponent(props) {
const criteria = [];
if (something) {
criteria.push(<strong>{ something }</strong>);
}
// join the jsx elements with `, `
const elements = criteria.reduce((accu, elem) => {
return accu === null ? [elem] : [...accu, ', ', elem]
}, null);
// render in a jsx friendly way
return elements.map((el, index) => <React.Fragment key={ index }>{ el }</React.Fragment> );
}
참고URL : https://stackoverflow.com/questions/34034038/how-to-render-react-components-by-using-map-and-join
'IT TIP' 카테고리의 다른 글
데이터 프레임의 모든 특정 값 바꾸기 (0) | 2020.10.18 |
---|---|
자바 스크립트로 라디오 버튼 확인 (0) | 2020.10.18 |
Java에서 스레드가 실행 중인지 어떻게 확인합니까? (0) | 2020.10.18 |
Java에서 정수를 float로 어떻게 변환 할 수 있습니까? (0) | 2020.10.18 |
'DateTime'이 'Nothing'인지 왜 확인할 수 없습니까? (0) | 2020.10.18 |