问题背景
我的 React Hook 有问题。
基本上,当用户更改显示顺序或用户在文本中输入搜索字符串时,我想重新渲染我的 <li>
组件(在下面的代码中命名为 elementsToDisplay
)输入元素来过滤它们。
//...import statements here...
function myHook(props) {
const [searchString, setSearchString] = useState('') // Initially empty searchstirng
const [order, setOrder] = useState('order1') // Ordering is initially order1
const [myObjects, setObjects] = useState(props.myObjects) // The objects needed to create the elements to display
const [elementsToDisplay, setElementsToDisplay] = useState([]) // The <li> elements to display (based on myObjects)
/*
IF THE SEARCHSTING OR THE ORDER GET CHANGED BY THE USER, CHANGE MY OBJECTS
*/
useEffect(() => {
var myObjectsCopy = [... props.myObjects]
myObjectsCopy.sort((a,b) => {
// Ordina in base a cosa l' utente ha selezionato dal sortByButton.
if (order == 'order1'){
// return some ordering
}
else if (order == 'order2'){
// return some ordering
}
else if (order == 'order3'){
// return some ordering
}
else{
// return some ordering
}
})
var newObjects = myObjectsCopy.filter(item => {
// filter based on searchsting
return item.productCode.toLowerCase().indexOf(searchString.toLowerCase()) >= 0
})
setObjects(newObjects)
console.log(myObjects[0]) // NOTE here myObjects get updated as expected everytime
}, [order, searchString])
/*
When myObjects change, so the <li> elements to display should (end they do!).
*/
useEffect(()=>{
var elements = get_elements_to_display()
setElementsToDisplay(elements)
console.log(elementsToDisplay[0]) // NOTE, elementsToDisplay change as expected!!!!!!
},[myObjects])
/*
Function that creates the <li> elements to display based on myObjects. NOTE works fine
*/
function get_elements_to_display(){
return myObjects.map((item, index) => {
var competitors = item.competitors
return(
<li key={index}>
<span className='produt-separator'/>
<ProductTable item={item} index={index} />
</li>
)
})
}
/*
Change the ordering to display the elements. NOTE Work as expected!!!
*/
function handleChangeOrder(e, value) {
e.preventDefault();
console.log(value) // NOTE the right ordering gets passed
setOrder(value)
console.log(order) // NOTE order gets updated as expected
}
/*
Render the component
*/
return (
<div>
<h1 className='page-title'>My Title</h1>
<input className="search-input" type='text'
onChange={e => setSearchString(e.target.value)}
placeholder='Cerca il toner o cartuccia per nome...'></input>
<span width="8px"/>
<SortByButton handleClick={handleChangeOrder}/>
<AddProductPopUp/>
<ul>
{elementsToDisplay}
</ul>
</div>
)
}
问题
问题是我的所有状态变量都按预期更改,但呈现的 <li>
组件保持不变。这很奇怪,因为它们存储在状态 elementsToDisplay
中,我可以看到每当我选择新的排序或尝试过滤我输入搜索字符串的元素时,它都会更新。
你能从我发布的示例代码中看出我是否做错了什么吗?
答案 0 :(得分:1)
(来自评论)
将列表 <li key={index}>
的键更改为除 index
之外的某个唯一标识符将修复它。
React 使用键来检测列表中的哪些项目发生了变化。由于您在非静态实例中使用索引作为键,然后对从中呈现的数组进行排序,因此索引的顺序保持不变。
答案 1 :(得分:0)
问题已在评论中回答。