我有一个>>> line = '> "start_nm":"BOSTON","bus_num":"1", "bus_num":"2","dest_nm":"NEW YorK"'
>>> re.findall(r':"(.*?)"', line)
['BOSTON', '1', '2', 'NEW YorK']
自定义组件,它只有一个select,options并监听onChange,然后我有一个Select
代码,该代码用一些变量初始化,选择一个选项后我的状态仍然具有初始化值
当我选择useReducer
时,ANOTHER
中的值为performSearch
ALL
有什么主意吗?
答案 0 :(得分:0)
If I had to guess I'd say that its because you are trying to call performSearch to log the console before the state is set. If you console log the state before you return your component you will probably be able to see the correct value in the state. I'm not sure what your use case is but if you want to use the value you can just return it in your function and not worry about the reducer and state at all. Like so:
const performSearch = (value) => {
console.log(value)
}
useEffect(() => {
performSearch('ALL')
},[])
<Select
onChange={(e) => {
const {value} = e.target
performSearch(value)
}}
items={[{key:"ALL",value:"ALL"},{key:"ANOTHER",value:"ANOTHER"}]}
/>
if you need to use the reducer then you can probably create a promise or I would just return the value to preformSearch and then set the state through your reducer from there like so:
const reducer = (state, newState) => ({ ...state, ...newState });
const [state, setState] = useReducer(reducer, {
filterStatus : 'ALL'
});
const performSearch = (value) => {
setState({filterStatus: value});
//Do your stuff with the value
console.log(value)
}
useEffect(() => {
//you can probably just set the value in preformSearch here manually or you can set it to the states value but setting to the states value would result in another render because you would set the state in performSearch again
performSearch(state.filterStatus)
},[])
<Select
onChange={(e) => {
const {value} = e.target
performSearch(value)
}}
items={[{key:"ALL",value:"ALL"},{key:"ANOTHER",value:"ANOTHER"}]}
/>
But like I said I'm not really sure what your end goal is with this component but for this use case I'm not sure you need to use the useReducer function at all.
答案 1 :(得分:0)
The problem is that you are calling performSearch() inside the onChange function, so when you set the new state you will only see the value from the previous state. Try to put the performSearch function outside of the onSelect function and you will get the correct output.