Laravel Livewire 错误 "must not be accessed before initialization"

Laravel Livewire error "must not be accessed before initialization"

我尝试直接使用 Livewire 绑定到模型属性,但出现此错误,有人帮忙吗?提前致谢。

Typed property App\Http\Livewire\V2\Settings\Locations::$country must not be accessed before initialization

 class Locations extends Component{
  public Country $country;
  use WithPagination;
  protected $rules = [
    'country.name' => 'required|min:100',
    'country.note' => 'required|min:100',
  ];

  public function SaveCountry(){
    $this->validate();
    $this->country->save();
    $this->reset();
    session()->flash('info','The country have been added successful.');
  }
 public function render(){
    return view('livewire.v2.settings.locations',[
        'countries' => Country::orderBy('order_num','desc')->paginate(10),
    ]);
  }
}

当您在PHP中定义变量的类型时,您需要为其提供一个默认值。

如果您的组件正在创建 Country,您可以在 mount 函数中将其设置为空 Country

public function mount()
{
    $this->country = new Country();
}

或者将 public Country $country 设置为现有的 Country