맵과 결합을 사용하여 반응 구성요소를 렌더링하려면 어떻게 해야 합니까?
Array of String을 표시하는 컴포넌트가 1개 있습니다.코드는 다음과 같습니다.
React.createClass({
render() {
<div>
this.props.data.map(t => <span>t</span>)
</div>
}
})
완벽하게 잘 작동하고 있습니다.props.data = ['tom', 'jason', 'chris']
, 페이지에 표시되는 결과는 다음과 같습니다.tomjasonchris
.
그 후 콤마를 사용하여 모든 이름을 등록하고 싶기 때문에 코드를 다음과 같이 변경합니다.
this.props.data.map(t => <span>t</span>).join(', ')
는 ""입니다.[Object], [Object], [Object]
.
렌더링할 반응 구성요소가 되기 위해 객체를 해석하는 방법을 모릅니다.제안해 주실 수 있나요?
은 단단 a a a를 사용하는 입니다.reduce()
, 이전 않고: without번 번 without :: without without without without without without without without 음 without 음 without without without without without without without 음 without 음 without 음 without without without without without without without without without without without without without without without without without
class List extends React.Component {
render() {
<div>
{this.props.data
.map(t => <span>{t}</span>)
.reduce((prev, curr) => [prev, ', ', curr])}
</div>
}
}
인수가 , 두면면면면면면면면면면면면면.reduce()
는 0이 아닌 인덱스 1에서 시작되며 React는 중첩된 배열에 대해 완벽하게 만족합니다.
아이템이 , 「1」은 「1」의 「1」의 「1」의 「1」의 「1」의 「1」의 「배열」이기 때문입니다.reduce()
두 번째 인수를 지정하지 않으면 빈 배열과 함께 느려집니다.일반적으로 빈 어레이에 대해 '이것이 비어 있습니다'와 같은 커스텀메시지를 표시하고 싶기 때문에 이것은 문제가 되지 않습니다.
타입스크립트 갱신
은 Typescript에서 사용할 수 (type-unsafe Typescript가 없는 경우).any
가 경우React.ReactNode
on type 。.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
인 '세퍼레이터를 붙입니다
컴포넌트 배열만 하면 .reduce
무무장장장장다다이러한 경우 보다 짧은 해결책은
{arr.map((item, index) => (
<Fragment key={item.id}>
{index > 0 && ', '}
<Item {...item} />
</Fragment>
))}
{index > 0 && ', '}
는 첫 번째 항목을 제외한 모든 배열 항목 앞에 쉼표 뒤에 공백이 표시됩니다.
다른 합니다.' and '
라고 치환할 수 .{index > 0 && ', '}
함께
{index > 0 && index !== arr.length - 1 && ', '}
{index === arr.length - 1 && ' and '}
React 16을 사용한 갱신: 문자열을 직접 렌더링할 수 있게 되었기 때문에 불필요한 것을 모두 제거함으로써 코드를 심플화할 수 있습니다.<span>
const list = ({ data }) => data.reduce((prev, curr) => [ prev, ', ', curr ]);
은 실제로 합니다. '배열'은 '배열'이기 때문입니다.prev
매번 배열이 됩니다.리액트는 충분히 스마트하지만, 맵의 각 결과에 키를 줄 때 리액션 확산 알고리즘이 깨지는 등의 문제가 발생하기 쉬운 것입니까.
★★★★★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(HTML [Respect]를 선택합니다)
<span>{t}</span>
반환되는 것은 문자열이 아니라 객체입니다.react documents를 체크합니다.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
마이 베리안트:
{this.props.data
.map(item => <span>{item}</span>)
.map((item, index) => [index > 0 && ', ', item ])}
es6를 사용하면 다음과 같은 작업을 수행할 수 있습니다.
const joinComponents = (accumulator, current) => [
...accumulator,
accumulator.length ? ', ' : '',
current
]
그런 다음 다음을 실행합니다.
listComponents
.map(item => <span key={item.id}> {item.t} </span>)
.reduce(joinComponents, [])
네스트된 배열을 사용하여 " "를 외부에 유지합니다.
<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>
이 방법은 효과가 있었습니다.
{data.map( ( item, i ) => {
return (
<span key={i}>{item.propery}</span>
)
} ).reduce( ( prev, curr ) => [ prev, ', ', curr ] )}
Pith에서 설명한 바와 같이 React 16을 사용하면 문자열을 직접 사용할 수 있으므로 문자열을 스판 태그로 감싸지 않아도 됩니다.Maarten의 답변을 바탕으로 커스텀메시지를 바로 처리하고 빈 배열에 오류를 발생시키지 않으려면 배열의 길이 속성에 3진 if 문을 사용하여 작업을 진행할 수 있습니다.다음과 같이 보일 수 있습니다.
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>
}
}
플랫 어레이가 반환됩니다.빈 첫 번째 어레이를 제공하여 반복할 수 없는 첫 번째 개체를 사용하여 사례를 처리하고 결과에서 불필요한 첫 번째 쉼표를 필터링합니다.
[{}, 'b', 'c'].reduce((prev, curr) => [...prev, ', ', curr], []).splice(1) // => [{}, 'b', 'c']
나 혼자만 불필요한 확산과 보금자리 짓기라고 생각하는 거야?간결하다는 점은 확실합니다만, 스케일 문제나 네스트된 어레이/프래그먼트의 처리 방법을 바꾸는 대응의 문제에 대해서는, 여지를 남겨 둡니다.
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>
어레이 하나, 네스트 없음.매력적인 방법 체인은 없지만 자주 사용하는 경우 어레이 프로토타입에 추가하거나 매핑 콜백이 필요한 함수로 래핑하여 한 번에 모두 수행할 수 있습니다.
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> );
}
★★★★★★★★★★★★★★★★ flatMap
( 모든 다음과 할 수 있습니다 (2022년 6월 현재)
const Demo = ({ data }) => <div>{data.flatMap(
(t, i) => [...(i ? [', '] : []), <span key={i}>{t}</span>]
)}</div>
ReactDOM.render(<Demo data={['tom', 'jason', 'chris']} />, document.body)
body { font-family: sans-serif; }
span { color: firebrick; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
은 "" == 0 "Callback" 을 합니다.[span]
, 그것은 .[text, span]
flatMap
map
의, 「 」2D 「 」[[span], [text, span], [text, span]]
[span, text, span, text, span]
반응하다
맵 뒤에 join()을 추가하여 태그 안에 넣습니다.
<span>{this.props.data.map((item) => item).join(', ')}</span>
{errors.username.map((e,k) => <span key={k}>{e} <br/></span>)}
내가 찾을 수 있는 가장 쉬운 방법이지
React 17에서는 다음과 같이 간단하게 할 수 있습니다.
<div>
{[1, 2, 3].map((e, i) => <p key={i}>{e}</p>)}
</div>
그리고 다음과 같이 렌더링됩니다.
<div>
<p>1</p>
<p>2</p>
<p>3</p>
</div>
언급URL : https://stackoverflow.com/questions/34034038/how-to-render-react-components-by-using-map-and-join
'source' 카테고리의 다른 글
카트 항목 메타 업데이트 방법 - woocommerce (0) | 2023.03.15 |
---|---|
요소가 DOM에 있을 때까지 기다리는 연장기 (0) | 2023.03.15 |
'data:font/woff.....' 글꼴 로드를 거부했습니다. 이는 "default-src 'self' 컨텐츠 보안 정책 지시문을 위반합니다.'font-src'는 (0) | 2023.03.15 |
Wordpress에서 홈 페이지로 다시 연결 (0) | 2023.03.15 |
Google이 JSON 응답 앞에 (1)을 추가하는 이유는 무엇입니까? (0) | 2023.03.15 |