admin管理员组文章数量:1427301
I got this code where I'm parsing dynamic text into separate lines and rendering individual ponents for each line of text.
I'm using the map
function to create an array for the elements and React demands a unique key for each element on the list.
I know usually it's not ideal to use index
as the key. But in this case, what else can I do?
QUESTION
Can I use index
as the key
for the elements in this case without having issues? What could go wrong?
Note1: I cannot use the values as the keys, because all lines might have the exact same values, hence they wouldn't be unique.
Note2: This code runs inside an Admin form for BlogPosts. I write some custom markup text, just like in the textarea for questions on StackOverflow and I need to parse it to give it proper styles when rendered out on the screen as a blog post. Like: **bold text**
, etc. And each line should be rendered as a different paragraph.
UPDATE:
I've read the article you all mentioned in ments and answer. And here's what the author points out:
Does my case meet all 3 requirements?
1 - Do they change? In theory they do.
2 - They have no ids.
3 - They are not filtered for sure. But are they reordered? What if you copy "line1\nline2\nline3"
paste into Notepad and change it to "line3\nline2\nline1"
and paste it back into the textarea
. Does it count as re-ordering? I just tested it and it renders just fine.
Anyway, so far I haven't run into any issues and it feels safe to use. But I would like an in-depth explanation of how it works in this case.
function App() {
const [inputValue,setInputValue] = React.useState("line1\nline2\nline3");
const lineItems = inputValue.split("\n").map((line,index) =>
<TextLine
key={index}
index={index}
value={line}
/>
);
return(
<React.Fragment>
<textarea
onChange={()=>setInputValue(event.target.value)}
value={inputValue}
style={{width: "300px", height: "60px"}}
/>
{lineItems}
</React.Fragment>
);
}
function TextLine(props) {
return(
<div>{props.value + " (key = " + props.index + ")"}</div>
);
}
ReactDOM.render(<App/>, document.getElementById("root"));
<script src=".8.3/umd/react.production.min.js"></script>
<script src=".8.3/umd/react-dom.production.min.js"></script>
<div id="root"/>
I got this code where I'm parsing dynamic text into separate lines and rendering individual ponents for each line of text.
I'm using the map
function to create an array for the elements and React demands a unique key for each element on the list.
I know usually it's not ideal to use index
as the key. But in this case, what else can I do?
QUESTION
Can I use index
as the key
for the elements in this case without having issues? What could go wrong?
Note1: I cannot use the values as the keys, because all lines might have the exact same values, hence they wouldn't be unique.
Note2: This code runs inside an Admin form for BlogPosts. I write some custom markup text, just like in the textarea for questions on StackOverflow and I need to parse it to give it proper styles when rendered out on the screen as a blog post. Like: **bold text**
, etc. And each line should be rendered as a different paragraph.
UPDATE:
I've read the article you all mentioned in ments and answer. And here's what the author points out:
Does my case meet all 3 requirements?
1 - Do they change? In theory they do.
2 - They have no ids.
3 - They are not filtered for sure. But are they reordered? What if you copy "line1\nline2\nline3"
paste into Notepad and change it to "line3\nline2\nline1"
and paste it back into the textarea
. Does it count as re-ordering? I just tested it and it renders just fine.
Anyway, so far I haven't run into any issues and it feels safe to use. But I would like an in-depth explanation of how it works in this case.
function App() {
const [inputValue,setInputValue] = React.useState("line1\nline2\nline3");
const lineItems = inputValue.split("\n").map((line,index) =>
<TextLine
key={index}
index={index}
value={line}
/>
);
return(
<React.Fragment>
<textarea
onChange={()=>setInputValue(event.target.value)}
value={inputValue}
style={{width: "300px", height: "60px"}}
/>
{lineItems}
</React.Fragment>
);
}
function TextLine(props) {
return(
<div>{props.value + " (key = " + props.index + ")"}</div>
);
}
ReactDOM.render(<App/>, document.getElementById("root"));
<script src="https://cdnjs.cloudflare./ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root"/>
Share
Improve this question
edited Jan 3, 2020 at 9:45
cbdeveloper
asked Jan 3, 2020 at 9:22
cbdevelopercbdeveloper
31.6k45 gold badges202 silver badges398 bronze badges
6
- I think that using index is not considered wrong but to be extra sure you can use UUID. This is just a precaution, not a deaddrop requirement. – vinayak shahdeo Commented Jan 3, 2020 at 9:27
- here you can find a good article on when it's not a very good idea to use index as key. medium./@robinpokorny/… – Ayyappa Gollu Commented Jan 3, 2020 at 9:31
- as long as you don't rearrange or filter the array, it's safe. – hotpink Commented Jan 3, 2020 at 9:31
- Yes, U can. Someone can say that u can't do that, it's kinda antipattern, but u can and in my opinion, it's no so bad. Even u can generate keys like key={"text-line${index}"}, if u want to make them unique – Diyaz Yakubov Commented Jan 3, 2020 at 9:32
- here is the answer that explains how should you use it: stackoverflow./a/46735689/6818430 – Navin Gelot Commented Jan 3, 2020 at 9:43
1 Answer
Reset to default 4Note: Don't use the index if the items have a unique id (and a non-primitives list should), because it's an anti-pattern as per documentation
When you don't have a unique id for the items, you can use the index.
const Numbers = ['One', 'Two', 'Three', 'Four'];
const App = () => (
<ul>
{Numbers.map (
(number, index) => <li key={index}>{number}</li>
)}
</ul>
)
Without a unique key, React couldn’t differentiate if the element was removed or just the content is changed.
Solutions for unique key...
1- You can create a function to generate unique keys/ids/numbers/strings and use that
2- You can use npm packages(library) like uuid, uniqid, shortid...
3- I remend using the unique ID you get from the database, If you get it.
本文标签:
版权声明:本文标题:javascript - Can I use index of map function as key for my React components containing dynamic unpredictable text? - Stack Overf 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745489251a2660528.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论